简体   繁体   中英

Accessing one namespace data member into another

How do I access the y (which is inside namespace n2), from n1 namespace: The test code is below:

#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;
}

I am getting below error: test.cpp:7:15: error: '::n2' has not been declared int m = ::n2::y;

Just change the order, so that n2 is resolvable inside 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM