2012-01-24 70 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接受派生*如果你告诉它标识符“派生”(即预先声明)的存在。事实上,如果你避免任何包含(自己的)头文件,其类型仅以这种方式使用(不需要完成),那么你很好。