Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如果全局变量中存在相同的变量,如何访问匿名命名空间变量_C++_Scope_Namespaces - Fatal编程技术网

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

C++ 如果全局变量中存在相同的变量,如何访问匿名命名空间变量,c++,scope,namespaces,C++,Scope,Namespaces,让我们想象一下情况: #include <iostream> int d =34; namespace { int d =45; } int main() { std::cout << ::d ; return 0; } #包括 int d=34; 名称空间 { int d=45; } int main() { std::cout如果没有其他帮助,您无法在main中消除两个ds之间的歧义 消除两者之间歧义的一种方法是在名称空间中创建一个引用

让我们想象一下情况:

#include <iostream>

int d =34;

namespace
{
    int d =45;
}

int main()
{
    std::cout << ::d ;
    return 0;
}
#包括
int d=34;
名称空间
{
int d=45;
}
int main()
{

std::cout如果没有其他帮助,您无法在
main
中消除两个
d
s之间的歧义

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

#include <iostream>

int d = 34;

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

int main()
{
    std::cout << dref  << std::endl;
    return 0;
}
#包括
int d=34;
名称空间
{
int d=45;
int&dref=d;
}
int main()
{

std::你不能这样做,除非你能把你的函数放在未命名的名称空间中(但你不能用
main
)。当然有很多解决办法,包括不使用相同的名称…我只想把它叫做
detail
,但是是的。
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;
}