2013-06-26 23 views
0

可有人請在下面的輸出解釋:理解 '使用' 關鍵字:C++

#include <iostream> 

using namespace std; 

namespace A{ 
    int x=1; 
    int z=2; 
    } 

namespace B{ 
    int y=3; 
    int z=4; 
    } 

void doSomethingWith(int i) throw() 
{ 
    cout << i ; 
    } 

void sample() throw() 
{ 
    using namespace A; 
    using namespace B; 
    doSomethingWith(x); 
    doSomethingWith(y); 
    doSomethingWith(z); 

    } 

int main() 
{ 
sample(); 
return 0; 
} 

輸出:

$ g++ -Wall TestCPP.cpp -o TestCPP 
TestCPP.cpp: In function `void sample()': 
TestCPP.cpp:26: error: `z' undeclared (first use this function) 
TestCPP.cpp:26: error: (Each undeclared identifier is reported only once for each function it appears in.) 
+0

你會期望發生什麼? –

+0

錯誤是誤導。我認爲發佈的代碼不是你編譯的代碼,並給出了發佈的錯誤。 – Nawaz

回答

4

我有另一個錯誤:

error: reference to 'z' is ambiguous

這是很清楚的me:z存在於兩個名稱空間中,編譯器不知道應該使用哪一個。 你知道嗎?通過指定命名空間來解決它,例如:

doSomethingWith(A::z); 
2

您會收到一條次優消息。更好的實現仍然會標記錯誤,但是說'z不明確',因爲這是問題而不是'未聲明'。

在點名稱z命中多件事情:A :: z和B :: z,並且規則是實現不能只選擇其中一個。您必須使用資格來解決問題。

4

using關鍵字用來

  1. 快捷方式的名稱,所以你不必型喜歡的東西std::cout

  2. 與模板(C++ 11)的typedef,即template<typename T> using VT = std::vector<T>;

在你的情況下,namespace用於防止名稱污染,這意味着兩個函數/ v無辜的人意外地分享了同一個名字。如果一起使用兩個using,這將導致模糊z。我的g ++ 4.8.1報告了錯誤:

abc.cpp: In function ‘void sample()’: 
abc.cpp:26:21: error: reference to ‘z’ is ambiguous 
    doSomethingWith(z); 
        ^
abc.cpp:12:5: note: candidates are: int B::z 
int z=4; 
    ^
abc.cpp:7:5: note:     int A::z 
int z=2; 
    ^

這是預期的。我不確定你正在使用哪個gnu編譯器,但這是一個可預測的錯誤。

+0

@soon感謝您使用關鍵字的更正。我無意中誤解了它。 – xis

+0

沒問題。 :) – soon

+0

AFAIU「using」的「typedef版本」也可以在沒有模板的情況下使用,例如, '使用integer = int;'。 – celtschk