2012-01-24 101 views
0

如果得到一個很簡單的問題(至少我希望如此),但我不知道該怎麼做才能告訴g ++以什麼順序「完成」我的類。我它降低到這個簡單的例子:gcc:交叉引用類編譯

base.h:

#ifndef BASE_H_ 
#define BASE_H_ 

#include "otherclass.h" 
class otherclass; 

class base { 
    public: 
     base(otherclass* other); 

    protected: 
     otherclass* m_other; 
}; 

#endif /* BASE_H_ */ 

derived.h:

#ifndef DERIVED_H_ 
#define DERIVED_H_ 

#include "base.h" 

class derived : public base { 
    public: 
     derived(otherclass* other); 
}; 

#endif /* DERIVED_H_ */ 

(二者對應cpp文件僅包含構造,其分配給定otherclass *到成員變量)

otherclass.h:

#ifndef OTHERCLASS_H_ 
#define OTHERCLASS_H_ 

#include "derived.h" 

class otherclass { 
    public: 
     otherclass(); 

    protected: 
     derived* m_derived; 
}; 

#endif /* OTHERCLASS_H_ */ 

otherclass.cpp:

#include "otherclass.h" 

otherclass::otherclass() { 
    m_derived = new derived(this); 
} 

因爲它可能是相關的,我會貼scons的整個輸出:

g++ -o base.o -c base.cpp 
g++ -o derived.o -c derived.cpp 
In file included from otherclass.h:4:0, 
      from base.h:4, 
      from base.cpp:1: 
derived.h:8:29: error: expected class-name before '{' token 
g++ -o main.o -c main.cpp 
In file included from base.h:4:0, 
      from derived.h:4, 
      from derived.cpp:1: 
otherclass.h:11:3: error: 'derived' does not name a type 

所以它看起來像基地是一個未知的類型,在這一點上與gcc並且預先聲明它顯然使它哭泣,因爲從一個不完整的類型派生是被禁止的。

我真的沒有看到問題在這裏(當然除了錯誤信息)。

有人能夠啓發我嗎?

回答

0

哈!搜索使用谷歌我的問題並沒有幫助我,但在計算器的相關問題做了標籤;)

供參考,該解決方案是這樣的:

在頭文件,如果你只有三分一類你應該

  1. 預先聲明類(這是我以前那樣),像

    類otherclass;

    in base.h and derived.h,and

    class derived;

    在otherclass.h

    ,但

  2. 包括相應的頭文件。 只有將它們包含在它們的.cpp文件中(這是我失敗的原因)。

說明:由於指針是相同的大小總是和他們的目標類型是唯一相關的,如果你真的有(即解引用)他們的工作,它完全足夠了GCC接受派生*如果你告訴它標識符「派生」(即預先聲明)的存在。事實上,如果你避免任何包含(自己的)頭文件,其類型僅以這種方式使用(不需要完成),那麼你很好。