如果在C++中以::
限定命名空间,这意味着什么?例如::testing::Test
.
::
是作用域解析运算符。它始终表示“在全局命名空间中搜索右侧的符号”。例如:
namespace testing {
int a = 1;
}
namespace foo {
namespace testing {
int a = 2;
}
int b = ::testing::a; // b has the value 1
int c = testing::a; // c has the value 2
}
testing
命名空间是全局命名空间中的一个,而不是另一个名为testing
的嵌套命名空间。namespace foo
{
struct gizmo{int n_;};
namespace bar
{
namespace foo
{
float f_;
};
};
};
int main()
{
using namespace foo::bar;
::foo::gizmo g;
g.n_;
}
foo
的命名空间。一个是顶级命名空间,挂在“全局”命名空间下,另一个嵌套在foo::bar
中。然后我们继续使用using namespace foo::bar
,意思是任何对gizmo
的未限定引用都将选择foo::bar::foo
中的引用。如果我们真的想要foo
中的引用,则可以使用显式限定符来实现:::foo::gizmo
。如果在变量名前加上::,它将解析为全局作用域的变量。这样,您就可以同时拥有本地变量testing和全局变量testing,并区分它们。
#include <iostream>
using namespace std;
int testing = 37;
int main()
{
int testing = 42;
cout << ::testing << ' ' << testing << endl;
}
输出结果将为 37 42
::
,它表示全局范围。testing::Test
将是一种相对路径(相对于König lookup),而::testing::Test
将是绝对路径。我希望这个比喻能让它更清晰,并且不会搞乱你的思维 :-)。这会调用所谓的限定名查找:
$3.4.3/1 - "类或命名空间成员的名称可以在将嵌套名称指定其类或命名空间的::作用域解析运算符(5.1)应用于后引用。在::作用域解析运算符之前查找名称时,对象、函数和枚举器名称将被忽略。如果找到的名称不是类名(第9条)或命名空间名称(7.3.1),则程序无效。"