为什么在使用命名空间时需要 c++ 命名空间说明符

Why do I need a c++ namespace specifier while using namespace?

本文关键字:命名空间 c++ 说明符 为什么      更新时间:2023-10-16

以下类 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()