c++ - 了解命名空间 using 指令

标签 c++ namespaces

在下面的程序中,我们有两个命名空间:

#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 [in A] that follows the member’s point of declaration.

我相信您必须将其理解为 b范围为 Ab 来看的声明。在哪里打印 A::b ,这实际上“遵循成员的声明点”,因此对于该行, b可以在A范围内找到。这是完全正确的。

关于c++ - 了解命名空间 using 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28103318/

相关文章:

c++ - 如何操作包含 `unique_ptr` 的类的实例?

c# - 在系统命名空间内创建 .net 系统库扩展的陷阱

php - CakePHP 和命名空间?

object - 如何避免 Rebol 中的对象函数和全局函数之间的名称冲突?

c++ - 日期格式的时间标记?

c++ - C++ 中嵌套类型/类的前向声明

c++ - c 中 undefined reference ...我做错了什么?

c++ - boost::geometry 和 std 命名空间与 Visual Studio 2013 冲突

javascript - javascript中的命名空间标准

r - 如何在我自己的函数中使用给定包的内部函数