为什么在使用命名空间时需要 c++ 命名空间说明符
Why do I need a c++ namespace specifier while using namespace?
以下类 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(无符号整数,无符号整数,无符号整数)"的未定义引用。
我不明白为什么我必须使用命名空间说明符作为全局函数"isValidDate"的前缀。
你能解释一下原因吗?谢谢
因为命名空间查找规则。
请参阅: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()
。
相关文章:
- 命名空间中具有.h和.cpp文件的类
- 从父命名空间重载类型
- 在命名空间中定义函数还是限定函数
- C++:对不存在的命名空间使用命名空间指令
- 通过继承类使用来自不同命名空间的运算符
- 使用命名空间时出现多个定义错误
- CUDA内核和数学函数的显式命名空间
- 嵌套的匿名命名空间
- CMakeLists.txt中的命名空间表示法
- 类是C++中的命名空间吗
- 在命名空间中使用全局命名空间中的函数
- 如何使 std::sort 在 std::swap 和我的命名空间的模板化交换之间没有名称冲突?
- '使用命名空间{嵌套在另一个命名空间中的某个命名空间}"
- 是否可以将函数导入命名空间,但不能导出它?
- C++ C++类中的命名空间降级
- 如何使用 soong 命名空间来有条件地编译模块
- 使用 Clang++ 有没有办法将文件作为命名空间等包含?
- 使用 make 编译 MPI,几个命名空间错误,例如"错误:未知类型名称'使用'?
- 如何通过命名空间调用非静态方法
- 在命名空间名称之前加上 :: 是什么意思?