我在下面尝试了这个虚拟代码来测试未命名的命名空间.
我有以下输出
- 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指令的唯一命名的命名空间.