yan*_*pas 5 c++ scope namespaces
让我们想象一下情况:
#include <iostream>
int d =34;
namespace
{
int d =45;
}
int main()
{
std::cout << ::d ;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这里的输出是34,因为::意味着全局命名空间.但如果我评论第3行输出是45,这很奇怪.
如果我使用std::cout << d ;- 我得到错误
s.cxx:12:15:错误:对'd'的引用是不明确的
在这种情况下,如何访问unnamed_namespace :: d?
PS:我已经读过,未命名的命名空间用于静态全局变量,仅在文件范围内可见
你不能两者间的歧义dS IN main没有别的东西的援助.
消除两者之间消除歧义的一种方法是在命名空间中创建引用变量,然后使用引用变量main.
#include <iostream>
int d = 34;
namespace
{
int d = 45;
int& dref = d;
}
int main()
{
std::cout << dref << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,为什么要把自己与同一个变量混淆?如果您有选项,请在命名空间中使用其他变量名称或为命名空间命名.
namespace
{
int dLocal = 45;
}
int main()
{
std::cout << dLocal << std::endl;
std::cout << d << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
要么
namespace main_detail
{
int d = 45;
}
int main()
{
std::cout << main_detail::d << std::endl;
std::cout << d << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)