访问匿名命名空间内的变量(c++)

Accessing the variable inside anonymous namespace (c++)

本文关键字:变量 c++ 命名空间 访问      更新时间:2023-10-16

我有以下代码,我不知道如何在此设置中访问匿名名称空间内的x。请告诉我怎么做?

#include <iostream>
int x = 10;
namespace
{
    int x = 20;
}
int main(int x, char* y[])
{
    {
        int x = 30; // most recently defined
        std::cout << x << std::endl; // 30, local
        std::cout << ::x << std::endl; // 10, global
        // how can I access the x inside the anonymous namespace?
    }
    return 0;
}

你不能!

您不能通过名称访问命名空间的成员,因为它没有成员。
它是匿名的。

您只能访问这些成员,因为它们已经被拉入作用域。

您必须从匿名相同作用域内的函数访问它:

#include <iostream>
int x = 10;
namespace
{
    int x = 20;
    int X() { return x; }
}
int main(int x, char* y[])
{
    {
        int x = 30; // most recently defined
        std::cout << x << std::endl; // 30, local
        std::cout << ::x << std::endl; // 10, global
        std::cout << X() << std::endl; // 20, anonymous
        // how can I access the x inside the anonymous namespace?
    }
    return 0;
}