简体   繁体   English

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

[英]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: 如何从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;
}

I am getting below error: test.cpp:7:15: error: '::n2' has not been declared int m = ::n2::y; 我得到以下错误:test.cpp:7:15:错误:':: n2'尚未声明int m = :: n2 :: y;

Just change the order, so that n2 is resolvable inside n1 : 只需更改顺序,即可在n1内解析n2:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 访问另一个班级成员 - Accessing another classes member 从另一个名称空间访问标准名称空间数据成员 - Accessing standard namespaces data members from another namespace 作为 LUA C++ 中另一个用户数据的成员访问用户数据 - Accessing user data as a member of another user data in LUA C++ 是否正在访问一个联合中的一个成员,该联合是从具有未定义或未指定的另一个成员集的联合复制的? - Is accessing one member in a union that copied from a union with another member set undefined or unspecified? 将一个名称空间隐藏在另一个名称空间中 - Hide one namespace in another 如何从另一个命名空间而不是全局命名空间定义函数和数据? - How to define functions and data from another namespace, not in the global one? 从一个 class 访问成员 function 的数据成员到另一个类的成员 function - Access data member of a member function from one class to another class's member function 是否有一种解决方法可以从另一个名称空间内部定义成员? - Is there a workaround to define a member from inside another namespace? 当外部名称空间的成员具有相同的名称时,访问未命名名称空间的成员 - Accessing member of an unnamed namespace when the outer namespace has a member with the same name 访问联合的数据成员时出错 - An error in accessing a data member of a union
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM