c – 具有未命名命名空间的名称空间,声明了相同的变量

我在下面尝试了这个虚拟代码来测试未命名的命名空间.

我有以下输出

ctor 1
 ctor 0
 3
 5

我对此有点困惑.

>我期待编译器发出错误,说它无法解决
关于:: m_a的歧义.相反,它始终指的是
少嵌套.总是这样吗? C遵循什么规则?
>似乎编译器按顺序创建变量CMyObj
写在文件上.总是这样吗?
>有没有办法访问最嵌套的m_a变量
来自main()?

class CMyObj{     
    public:
    CMyObj(int a){std::cout  << "ctor " << a << std::endl; }
 };
 namespace a{ 
      namespace{
           int m_a=4;
           int m_b=5;
           CMyObj m_obj(1);
      }  
 }
 namespace a{
      int m_a=3;
      CMyObj m_obj(0);
 }
 int main(){
      std::cout << a::m_a << std::endl; // which one?
      std::cout << a::m_b << std::endl; // how this is possible?
      return 0;
 }

解决方法

我没有C 03标准来检查那里的措辞,所以我将引用Fdis n3290.我认为这个问题的答案可以在3.4.3.2/2中的限定名称查找规则中找到:

For a namespace X and name m,the namespace-qualified lookup set S(X,m) is defined as follows: Let S0(X,m) be the set of all declarations of m in X and the inline namespace set of X (7.3.1). If S0(X,m) is not empty,S(X,m) is S0(X,m); otherwise,m) is the union of S(Ni,m) for all namespaces Ni nominated by using-directives in X and its inline namespace set.

现在,请记住,未命名的命名空间是具有using指令的唯一命名的命名空间.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...