2014年3月4日 星期二

Field `x' has incomplete type?

       當你有兩個Class,CLASS_A與CLASS_B時,如果再主程式中並沒有用include將其header file include進來時,而使用forward reference 時會出現下列的錯誤訊息:

aggregate `CLASS_B bb' has incomplete type and cannot be defined
aggregate `CLASS_A aa' has incomplete type and cannot be defined

範例:
main.cpp
class CLASS_A;
class CLASS_B;

int main()
{
     CLASS_A a;
     CLASS_B b;
     return 0;
}

CLASS_A.h
class CLASS_A{
     public:
            CLASS_A(){}
};

CLASS_B.h
class CLASS_B{
     public:
            CLASS_B(){}
};

         另外,你也許用CLASS_B的物件當做 CLASS_A建構的參數,你也許會看到下面的錯誤訊息:
aggregate `CLASS_B bb' has incomplete type and cannot be defined 
variable `CLASS_A aa' has initializer but incomplete type

範例:
main.cpp
class CLASS_A;
class CLASS_B;

int main()
{
     CLASS_B b;
     CLASS_A a(&b);
     return 0;
}

CLASS_A.h
class CLASS_B; // Forward reference declare

class CLASS_A{
     public:
            CLASS_A( CLASS_B *pB){}
};

      這些是典型的忘記將 header file inlude進來的問題,只要將該檔案的header file include到 main.cpp中即可。會發生 incomplete type 是因為編譯器在編譯時需要知道物件的大小,但是我們 在還不知道class定義在何處,就將其拿來宣告物件使用。 其詳細的 incomplete type 的解釋請參考 下面相關鏈結。

[Keyword]
    incomplete type ; incomplete type + C++ + Class

[相關鏈結]
Incomplete class declarations (C++ only)
Incomplete Type
Forward declarations in C++
C++ Tip: Forward Declaration
forward declaration 唯一的好处只是可以让编译快一点

沒有留言: