4

这个问题已经在命名命名空间内的未命名命名空间链接中讨论过, 但没有提供关于如何访问嵌套在命名命名空间下的未命名命名空间变量的完美答案,以防两个变量相同

考虑本准则

namespace apple {   
    namespace {
                 int a=10;
                 int b=10;
              }
   int a=20;
}


int main()
{
cout<<apple::b; //prints 10
cout<<apple::a; // prints 20
}

未命名的命名空间"variable a"总是隐藏的。如何访问"variable a"未命名的命名空间?

在命名空间中声明未命名的命名空间是否合法?

4

2 回答 2

1

未命名的命名空间"variable a"总是隐藏的。如何访问"variable a"未命名的命名空间?

看起来您根本无法限定封闭命名空间之外的未命名命名空间。

好吧,这是解决歧义的方法:

namespace apple {   
    namespace {
        int a=10;
    }

    int getPrivateA() {
        return a;
    }

    int a=20;
}

int main() {
    cout<<apple::getPrivateA() << endl;
    cout<<apple::a << endl;
}

请参阅现场演示


尽管我知道这并不能完全回答您的问题(除了将未命名的名称空间嵌套在另一个名称空间中是否合法之外)。
我将不得不进一步研究第 3.4 和 7.3 章的c++ 标准规范,以便给你一个明确的答案,为什么你想做的事情不可能。

于 2017-08-25T19:18:49.620 回答
0

前几天我读到了这篇文章,并得到了“如何访问未命名命名空间的“变量 a”?”的答案。

我完全知道这不是一个完美的答案,但这是一种从未命名的命名空间访问“a”的方法。

#include <iostream>
#include <stdio.h>

namespace apple {
        namespace {
                     int a=257;
                     int b=10;
                  }
       int a=20;
    }

using namespace std;

int main() {

int* theForgottenA;

// pointer arithmetic would need to be more modified if the variable before 
// apple::b was of a different type, but since both are int then it works here to subtract 1
theForgottenA = &apple::b - 1; 

cout << *theForgottenA; //output is 257

}
于 2017-08-30T16:45:26.840 回答