c++ - 将一个命名空间数据成员访问到另一个

标签 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;

最佳答案

只需更改顺序,使 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;
}

关于c++ - 将一个命名空间数据成员访问到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48335093/

相关文章:

ruby-on-rails - rails 3 命名空间 Controller 和路由

c++ - 函数不返回应该返回的内容 - C++

android - WebCachedImageView 错误 res xml 命名空间

c++ - boost-asio 作为守护进程的 "template"

c++ - 链接 Visual Studio 2008 Express '/Mtd' 设置时 Boost 崩溃

django - Django REST Framework 中的命名空间超链接序列化程序

c# - XElement 不应该从其父 Xelement 继承命名空间吗?

c++ - opencv 命名空间和 c、c++ 函数

C++ cmake 错误 BOOST_ROOT DOXYGEN

c++ - 如何在 Blackberry 10 Cascades 的 qml、C++ qt 中响应单击 ListView 中的列表项