2009-09-14 46 views
1

我很好奇我的typedef方法對我的構建有什麼影響。轉發typedef聲明,影響構建時間和命名約定

請考慮下面的例子。

#include "SomeClass.h" 

class Foo 
{ 
    typedef SomeClass SomeOtherName; 

    SomeOtherName* storedPointer; 

    void setStoredPointer(SomeOtherName* s); 
} 

void Foo::setStoredPointer(SomeOtherName* s) 
{ 
    storedPointer = s; 
} 

每當結束了像上面的情況下,這種驅動的typedef到頭部文件,因此,需要我#包括它在頭文件。我擔心缺乏前瞻性聲明可能會導致更長的構建時間。

基於此發表評論:

Forward declaration of a typedef in C++

我可以轉發聲明類,類型定義引用或指針,然後#包括.cpp文件中。這應該允許更快的構建時間。我的結論是否正確?

如果是的話,我會用一個typedef落得像這樣:

typedef SomeClass* SomeOtherNamePtr; 
typedef SomeClass& SomeOtherNameRef; 
typedef const SomeClass* SomeOtherNameConstPtr; 
typedef const SomeClass& SomeOtherNameConstRef; 

這看起來並不像很乾淨的代碼給我,我想我已經讀文章/貼子(不一定SO)建議不要這樣做。

你覺得這可以接受嗎?更好的選擇?


更新: 使用邁克爾·伯爾的答案,我能夠解決只有指針和引用的情況。然而,當我嘗試在我的函數中使用sizeof()時遇到了一個問題。例如,說班級具有以下功能:

//Foo.h 
class Foo 
{ 
    typedef class SomeClass SomeOtherName; 

    void doSomething(const SomeOtherName& subject) 
} 

//Foo.cpp 
#include "Foo.h" 
#include "SomeClass.h" 
void Foo::doSomething(const SomeOtherName& subject) 
{ 
    sizeof(subject); //generates error C2027: use of undefined type 'SomeClass'; 
    sizeof(SomeClass); //generates same error, even though using the sizeof() 
         //the class that has been #include in the .cpp. Shouldn't 
         //the type be known by now? 
} 

或者,這將工作。

//Foo.h 
class SomeClass; 
class Foo 
{ 
    void doSomething(const SomeClass& subject) 
} 

//Foo.cpp 
#include "Foo.h" 
#include "SomeClass.h" 
void Foo::doSomething(const SomeClass& subject) 
{ 
    sizeof(subject); 
    sizeof(SomeClass); 
} 

我正在使用Microsoft Visual C++ 6.0。這是編譯器的錯誤還是這是一般的標準?

在出現該錯誤的示例中,請注意sizeof(SomeClass)是正在使用typedef的原始類,而不是在Foo中創建的新typedef類型。我感到驚訝的是,在typedef中進行前向聲明會限制我對正在使用typedef的類執行任何操作的能力。


跟帖: 只是測試它使用Xcode編譯,我相信我的sizeof問題是一個Visual C++ 6.0編譯器的問題。我猜想XCode編譯器可能是正確的,但我現在沒有其他任何東西可以嘗試。所以,儘管這些信息豐富,但我個人目前的任務並不順利,因爲最好的答案不適合我的情況。

回答

2

typedef class SomeClass SomeOtherName; 

爲你做的把戲?

因此,只使用指針或引用的typedef的編譯單元不需要#include標頭SomeClass

+0

我嘗試了你的建議,它確實解決了類完全使用指針和引用處理的具體情況。但是,我發現在.cpp文件中嘗試和類(在sizeof())上做類似的事情,仍然有問題。我會用一個例子更新這個問題。 – 2009-09-14 04:18:21

+0

這是設計。如果不知道對象的實際定義,編譯器無法計算出對象的大小。 – 2009-09-14 04:29:30

+0

當處理一個不兼容的類型時,你可以聲明引用或指向類型的指針,但是你不能做其他事情,因爲所有的編譯器知道的是名字,但沒有其他類型。使用不完整類型的refs/pointers允許類的頭文件避免依賴於另一個頭,但是實現仍然需要包含目標類型的完整聲明。使用不完整的類型可能會阻止您能夠實現內聯方法。 – 2009-09-14 04:45:37

0

我的結論是否正確?

是的。一個在你提到的問題的回答表明,你可以:

//forward declaration instead of #include "SomeClass.h" 
class SomeClass; 
//now this works even without #include "SomeClass.h" 
typedef SomeClass SomeOtherName; 

這看起來並不像很乾淨的代碼,我

我沒有看到你的typedef添加任何值;相反,我可能會提前申報SomeClass,然後直接使用'const SomeClass&'。