在下面的程序中,我们有两个命名空间:
#include <iostream>
namespace B
{
int c = 42;
}
namespace A
{
using namespace B;
int a = 442;
}
namespace B
{
int b = 24;
}
int main()
{
std::cout << A::a << std::endl; //442
std::cout << A::b << std::endl; //24
std::cout << A::c << std::endl; //42
}
<强> DEMO
我认为该程序的行为已被 N4296::3.3.6/1 [basic.scope.namespace] 涵盖
:
A namespace member name has namespace scope. Its potential scope includes its namespace from the name’s point of declaration (3.3.2) onwards; and for each using-directive (7.3.4) that nominates the member’s namespace, the member’s potential scope includes that portion of the potential scope of the using-directive that follows the member’s point of declaration.
因此,在命名空间 A
的情况下,成员 b
的潜在范围不应包含程序的任何部分,因为该成员已声明然后是 using 指令
。但实际上可以通过限定名称查找找到它。怎么了?
最佳答案
如果您再次阅读此片段:
the member’s [
b
's] potential scope includes that portion of the potential scope of the using-directive [inA
] that follows the member’s point of declaration.
我相信您必须将其理解为 b
范围为 A
从 b
来看的声明。在哪里打印 A::b
,这实际上“遵循成员的声明点”,因此对于该行, b
可以在A
范围内找到。这是完全正确的。
关于c++ - 了解命名空间 using 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28103318/