如果全局变量中存在相同的变量,如何访问匿名名称空间变量 [英] How to access to anonymous namespace variable if the same variable exists in global
问题描述
让我们想象一下情况:
#include <iostream>
int d =34;
namespace
{
int d =45;
}
int main()
{
std::cout << ::d ;
return 0;
}
此处的输出为34,因为::
表示全局名称空间.但是,如果我在第三行添加注释,则输出为45,这是 strange .
Here the output is 34, because ::
means global namespace. But If I comment 3rd line the output is 45, which is strange.
如果我使用std::cout << d ;
-我会收到错误
If I use std::cout << d ;
- I get error
s.cxx:12:15:错误:对"d"的引用不明确
s.cxx:12:15: error: reference to ‘d’ is ambiguous
在这种情况下如何访问unnamed_namespace :: d?
How can I access unnamed_namespace::d in this scenario?
PS:我已经读到未命名的名称空间用于静态全局变量,也就是仅在文件范围内可见的
PS: I've read that unnamed namespace is used for static global variables aka visible only in file scope
推荐答案
在没有其他帮助的情况下,您不能在main
中的两个d
之间进行歧义消除.
You cannot disambiguate between the two d
s in main
without the aid of something else.
消除两者歧义的一种方法是在名称空间中创建引用变量,然后在main
中使用引用变量.
One way to disambiguate between the two is to create a reference variable in the namespace and then use the reference variable in main
.
#include <iostream>
int d = 34;
namespace
{
int d = 45;
int& dref = d;
}
int main()
{
std::cout << dref << std::endl;
return 0;
}
但是,为什么要将自己与同一个变量混淆?如果可以的话,请在名称空间中使用其他变量名称,或为名称空间命名.
But then, why confuse yourself with the same variable? If you have the option, use a different variable name in the namespace or give the namespace a name.
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;
}
这篇关于如果全局变量中存在相同的变量,如何访问匿名名称空间变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!