访问另一个名称空间数据成员

时间:2018-01-19 06:09:14

标签: c++ namespaces

如何从n1命名空间访问y(在命名空间n2中): 测试代码如下:

#include<iostream>
using namespace std;

namespace n1
{
    int x =  20;
    int m = ::n2::y;
    void printx()
    {
        cout << "n1::x is " << x << endl;
        cout << "n2::y is " << m << endl;
    }
}

namespace n2
{
    int y = 10;
}

int main()
{
    cout << n1::x << endl;
    n1::printx();
    cout << n2::y << endl;

    return 0;
}

我收到以下错误: test.cpp:7:15:错误:':: n2'尚未声明      int m = :: n2 :: y;

1 个答案:

答案 0 :(得分:2)

只需更改顺序,以便n2在n1中可解析:

#include<iostream>
using namespace std;


namespace n2
{
    int y = 10;
}

namespace n1
{
    int x =  20;
    int m = n2::y;
    void printx()
    {
        cout << "n1::x is " << x << endl;
        cout << "n2::y is " << m << endl;
    }
}


int main()
{
    cout << n1::x << endl;
    n1::printx();
    cout << n2::y << endl;

    return 0;
}