为什么我必须为嵌套匿名名称空间中的函数指定外部名称空间

Why do I have to specify the outer namespace for a function in a nested anonymous namespace?

本文关键字:空间 函数 外部 嵌套 为什么      更新时间:2023-10-16

给定一个命名空间a。内部是一个带有函数f和类X的匿名命名空间,也带有函数f:当从a::X::f调用匿名f时,为什么必须指定外部命名空间a::作为限定符?

作为一个最小的例子:

#include <iostream>
using namespace std;
namespace A {
 namespace {
     int f( int i ) { return i; }
 }
 class X {
 public:
     static int f() { A::f( 10 ); }
 };
}

int main()
{
   cout << A::X::f() << endl; 
   return 0;
}

因为在X::f的范围内,非限定名称f指的是X::f,而不是任何其他f。在作用域内声明的名称将隐藏外部作用域中具有相同名称的任何内容。