【发布时间】: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”的前缀。
你能解释一下原因吗? 谢谢
【问题讨论】:
-
请停止在头文件中使用
using namespace std;。延伸阅读:Why is “using namespace std” in C++ considered bad practice? -
为什么
ADate的构造函数采用常规的ints,而isValidDate采用unsigned ints?你有点乞求签名/未签名的问题。 -
函数
isValidDate的原型在头文件的命名空间A内,所以它真的不是全局的。 -
是时候进行代码审查了(一旦你修复了这个错误)。结帐codereview.stackexchange.com
标签: c++ namespaces