2011-04-11 163 views
2

我對命名空間內一個簡單的問題:命名空間範圍問題

  1. 我有兩個命名空間,A和B,其中嵌套在A,B
  2. 我宣佈A.裏面的typedef一些
  3. 我在B中聲明一個類(它在A中)

要從B中訪問類型定義(在A中聲明),是否需要執行「using namespace A;」

即:

B.hpp:

using namespace A; 

namespace A { 
namespace B { 

    class MyClass { 

    typedeffed_int_from_A a; 
    }; 

} 
} 

這似乎是多餘的...這是正確的嗎?

回答

4

要從B中訪問類型定義(在A中聲明),是否需要執行「using namespace A;」


但是如果有一個typedef或具有相同的名稱的typedef,在命名空間B定義的其它一些符號,那麼你需要寫:

A::some_type a; 

讓我們做一個簡單的實驗來理解這一點。

考慮以下代碼:(必須閱讀評論

namespace A 
{ 
    typedef int some_type; //some_type is int 

    namespace B 
    { 
     typedef char* some_type; //here some_type is char* 

     struct X 
     { 
       some_type  m; //what is the type of m? char* or int? 
       A::some_type n; //what is the type of n? char* or int? 
     }; 

     void f(int) { cout << "f(int)" << endl; } 
     void f(char*) { cout << "f(char*)" << endl; } 
    } 
} 

int main() { 
     A::B::X x; 
     A::B::f(x.m); 
     A::B::f(x.n); 
     return 0; 
} 

輸出:

f(char*) 
f(int) 

這證明的m類型char*nint如預期或預期的那樣。

在線演示:http://ideone.com/abXc8

4

不,您不需要using指令;因爲B嵌套在A的內部,所以A的內容在B的範圍內。