2010-11-08 39 views
5

假設我正在創建一個項目,並且我在名爲Project的名稱空間中擁有最多項目。我在名爲MainProject的名稱空間Project中定義了一個類。在源文件中使用名稱空間的C++

在源文件中,爲了實現這個類,我該做'使用命名空間項目'嗎?還是將它包裝在'命名空間項目{...}'巢中?

回答

7

給定一個標題 「NH」:

namespace n{ 
    extern void f(); 
} 

以下在命名空間n定義f()(從現在起,我將把它作爲n::f

#include "n.h" 
using namespace n; 

void f(){ } 

如果你試圖在任何地方參考n::f,你會得到一個鏈接時間錯誤。上面在全局命名空間中定義了一個f,這確實定義了n::f

#include "n.h" 
void n::f(){ } 

這也確實:

#include "n.h" 
namespace n{ 
    void f(){ } 
} 

,但有一個缺點:如果你誤鍵入名稱或簽名,您將添加一個新功能命名空間,並留下void n::f()不確定,導致一個半煩人的鏈接時間錯誤。

當類參與,事情有一點不同:

namespace n{ 
    class c{ 
    void f(); 
    }; 
    extern c operator + (const c&, const c&); // I'll use Matthieu M.'s example 
} 

這會好起來的,因爲沒有全球c

#include "n.h" 
using namespace n; 
void c::f(){ } 

但以下原因會導致鏈接時如果您嘗試添加兩個c,則出錯的原因與第一次嘗試定義n::f()時的原因相同:

#include "n.h" 
using namespace n; 
c operator + (const c &a, const c &b){ /* blah blah */ } // define global + 

這種情況也會導致鏈接時錯誤(或者甚至一個編譯錯誤,不同的地方::c::f定義):

class c{ // a global c, defined in some header somewhere 
    void f(); 
}; 

#include "n.h" 
using namespace n; 
void c::f(){ } // define the global c::f (a possible redefinition) and n::c::f remains undefined! 
3

兩種方法都很好,它確實是一個品味(或命名衝突)的問題。我通常不做任何事情,只是在需要的地方添加命名空間。

2

重新打開相同的名稱空間然後提供類的實現而不是在不同的(封閉的)名稱空間中會更好。這主要來自模塊化,並且它是相關的收益角度。

1

using namespace xxx;語法存在(細微)問題。其中名稱衝突...

一般來說,最好不要使用它。我建議重新打開命名空間,而不是在名稱空間名稱前加上標識符,但這更多的是品味。微妙的問題

例子:

// header 
namespace foo 
{ 
    struct Bar 
    { 
    explicit Bar(int i); 
    int x; 
    }; 
    Bar operator+(Bar lhs, Bar rhs); 
} 

// source 
#include "the header here" 

using namespace foo; 

Bar operator+(Bar lhs, Bar rhs) 
{ 
    return Bar(lhs.x + rhs.x); 
} 

這引發編譯錯誤。

相關問題