簡體   English   中英

訪問一個名稱空間數據成員到另一個

[英]Accessing one namespace data member into another

如何從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;

只需更改順序,即可在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM