使用指令理解命名空间
Understanding namespace using directive
在下面的程序中我们有两个命名空间:
#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
}
我认为程序的行为被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.
因此,在 namespace A
的情况下,成员 b
的潜在范围不应该包含程序的任何部分,因为该成员的声明晚于 using directive
。但实际上它可以通过限定名称查找找到。怎么了?
如果你再读一遍这个片段:
the member’s [b
's] potential scope includes that portion of the potential scope of the using-directive [in A
] that follows the member’s point of declaration.
我相信您必须将其解读为从 b
的声明开始,b
就在 A
的范围内。在打印 A::b
的地方,实际上是 "follow the member's point of declaration",因此对于该行,可以在 A
的范围内找到 b
。这是完全正确的。
在下面的程序中我们有两个命名空间:
#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
}
我认为程序的行为被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.
因此,在 namespace A
的情况下,成员 b
的潜在范围不应该包含程序的任何部分,因为该成员的声明晚于 using directive
。但实际上它可以通过限定名称查找找到。怎么了?
如果你再读一遍这个片段:
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
的声明开始,b
就在 A
的范围内。在打印 A::b
的地方,实际上是 "follow the member's point of declaration",因此对于该行,可以在 A
的范围内找到 b
。这是完全正确的。