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

前端之家收集整理的这篇文章主要介绍了c – 具有未命名命名空间的名称空间,声明了相同的变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在下面尝试了这个虚拟代码来测试未命名的命名空间.

我有以下输出

  1. ctor 1
  2. ctor 0
  3. 3
  4. 5

我对此有点困惑.

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

  1. class CMyObj{
  2. public:
  3. CMyObj(int a){std::cout << "ctor " << a << std::endl; }
  4. };
  5. namespace a{
  6. namespace{
  7. int m_a=4;
  8. int m_b=5;
  9. CMyObj m_obj(1);
  10. }
  11. }
  12. namespace a{
  13. int m_a=3;
  14. CMyObj m_obj(0);
  15. }
  16. int main(){
  17. std::cout << a::m_a << std::endl; // which one?
  18. std::cout << a::m_b << std::endl; // how this is possible?
  19. return 0;
  20. }

解决方法

我没有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&C++相关文章