如果全局中存在相同的变量,如何访问匿名命名空间变量

时间:2016-01-05 00:26:04

标签: c++ scope namespaces

让我们想象一下情况:

#include <iostream>

int d =34;

namespace
{
    int d =45;
}

int main()
{
    std::cout << ::d ;
    return 0;
}

此处输出为34,因为::表示全局命名空间。但如果我评论第3行,则输出为45,这是奇怪

如果我使用std::cout << d ; - 我收到错误

  

s.cxx:12:15:错误:对'd'的引用含糊不清

如何在此方案中访问unnamed_namespace :: d?

PS:我已经读过未命名的命名空间用于静态全局变量,仅在文件范围内可见

1 个答案:

答案 0 :(得分:9)

如果没有其他内容,您无法消除dmain的{​​{1}}之间的歧义。

消除两者之间歧义的一种方法是在命名空间中创建引用变量,然后在main中使用引用变量。

#include <iostream>

int d = 34;

namespace
{
    int d = 45;
    int& dref = d;
}

int main()
{
    std::cout << dref  << std::endl;
    return 0;
}

但是,为什么要将自己与同一个变量混淆?如果您有选项,请在命名空间中使用其他变量名称,或者为命名空间命名。

namespace
{
    int dLocal = 45;
}

int main()
{
    std::cout << dLocal << std::endl;
    std::cout << d  << std::endl;
    return 0;
}

namespace main_detail
{
    int d = 45;
}

int main()
{
    std::cout << main_detail::d << std::endl;
    std::cout << d  << std::endl;
    return 0;
}