【问题标题】:Why do I need a c++ namespace specifier while using namespace?为什么在使用命名空间时需要 C++ 命名空间说明符?
【发布时间】:2016-04-22 18:23:22
【问题描述】:

下面的 ADate 类声明被命名空间 A 包围
.h 文件

#ifndef ADATE_H
#define ADATE_H

namespace A{

    class ADate
    {
    public:
        static unsigned int daysInMonth[];

    private:
        int day;
        int month;
        int year;

    public:
        ADate(const unsigned int day, const unsigned int month, const unsigned int year);
    };

    bool isValidDate(const unsigned int day, const unsigned int month, const unsigned int year);
}


#endif // ADATE_H

.cpp 文件:

#include "adate.h"

using namespace A;

unsigned int ADate::daysInMonth[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };

ADate::ADate(const unsigned int day, const unsigned int month, const unsigned int year) :
    day{day},
    month{month},
    year{year}
{
    if(!isValidDate(day,month,year)){
        throw string{"invalid Date"};
    }
}

bool isValidDate(const unsigned int day, const unsigned int month, const unsigned int year)
{
    if(month < 1 || month > 12){
        return false;
    }
    if(day < 1 || day > ADate::daysInMonth[month-1]){
        return false;
    }
    if(year < 1979 || year > 2038){
        return false;
    }
    return true;
}

应该认为上面的代码可以编译成功。然而,情况并非如此,导致对 `A::isValidDate(unsigned int, unsigned int, unsigned int)' 的未定义引用发生。

我不明白为什么我必须使用命名空间说明符作为全局函数“isValidDate”的前缀。

你能解释一下原因吗? 谢谢

【问题讨论】:

标签: c++ namespaces


【解决方案1】:

由于命名空间查找规则。

见:http://en.cppreference.com/w/cpp/language/lookup

对于变量、命名空间、类等(除了函数),名称查找必须生成单个声明才能编译程序。

对于函数名称查找可以关联多个声明(然后通过参数比较来解决)。

所以:

bool isValidDate(const unsigned int day, const unsigned int month, const unsigned int year)
{
   // CODE
}

既是声明又是定义。命名空间解析不需要将函数名称解析为 A::isValidDate() 函数,因此不需要。相反,它在isValidDate() 的当前作用域中添加了另一个声明。

【讨论】:

  • 好的,谢谢你的解释。只是为了完整性:成员方法不需要说明符,因为在 namspace 中声明的类的类说明符。对吗?
  • @PaceyW。正确的类名必须准确地解析为特定的类(如果多个类匹配这是一个编译时错误)。由于现在与类完全匹配,因此您可以将定义与声明匹配。
猜你喜欢
  • 2011-01-14
  • 1970-01-01
  • 2020-11-24
  • 2022-07-06
  • 2015-02-10
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 2011-01-05
相关资源
最近更新 更多