2016-09-16 149 views
3

我有以下代碼,我不知道如何訪問此設置中的匿名命名空間內的x。請告訴我如何?訪問匿名命名空間中的變量(C++)

#include <iostream> 

int x = 10; 

namespace 
{ 
    int x = 20; 
} 

int main(int x, char* y[]) 
{ 
    { 
     int x = 30; // most recently defined 
     std::cout << x << std::endl; // 30, local 
     std::cout << ::x << std::endl; // 10, global 
     // how can I access the x inside the anonymous namespace? 
    } 

    return 0; 
} 
+4

你不能。不要這樣做。 –

+0

非常感謝... !!! –

+0

一些相關的閱讀:http://stackoverflow.com/questions/9622874/unnamed-namespace-access-rules – NathanOliver

回答

1

You can't!

無法通過其名稱訪問命名空間的成員,因爲它沒有一個。
它是匿名的。

您只能通過他們已被拉入範圍訪問這些成員。

+0

謝謝,那麼爲什麼人們在命名空間內創建了這樣一個無法訪問的變量?由於他們已經被納入範圍而獲得了什麼意思?你能告訴我更具體嗎? :) –

+0

@DongkyuChoi:這意味着該對象不能在該翻譯單元之外被直接引用。它在某種意義上使對象成爲「文件本地」。它已被拉入該「文件」的範圍,因此您可以在那裏使用它(如您在問題中所示),但無處可用。 –

0

你必須從匿名同一範圍內的功能訪問:

#include <iostream> 

int x = 10; 

namespace 
{ 
    int x = 20; 
    int X() { return x; } 
} 

int main(int x, char* y[]) 
{ 
    { 
     int x = 30; // most recently defined 
     std::cout << x << std::endl; // 30, local 
     std::cout << ::x << std::endl; // 10, global 
     std::cout << X() << std::endl; // 20, anonymous 
     // how can I access the x inside the anonymous namespace? 
    } 

    return 0; 
} 
+0

哇,我明白了!非常感謝您的回答!! –

+0

不,不,不!因爲X()是唯一的,所以如果你添加一個外部函數X(),那麼這個將隱藏你的內部X()。 – Raindrop7

+1

能夠訪問匿名命名空間內的數據考慮:永遠不要使用相同的名稱聲明任何外部數據。 – Raindrop7