Compilation gcc:交叉引用类编译

Compilation gcc:交叉引用类编译,compilation,incomplete-type,Compilation,Incomplete Type,如果我有一个非常简单的问题(至少我希望如此),但我不知道如何告诉g++以什么顺序“完成”我的类。我把它简化为一个简单的例子: 基础h: #ifndef BASE_H_ #define BASE_H_ #include "otherclass.h" class otherclass; class base { public: base(otherclass* other); protected: otherclass* m_other; };

如果我有一个非常简单的问题(至少我希望如此),但我不知道如何告诉g++以什么顺序“完成”我的类。我把它简化为一个简单的例子:

基础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_ */
h.h:

#ifndef DERIVED_H_
#define DERIVED_H_

#include "base.h"

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

#endif /* DERIVED_H_ */
(两个对应的.cpp文件仅包含将给定的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);
}
因为它可能是相关的,所以我将粘贴SCON的整个输出:

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来说似乎是一个未知的类型,并且预先声明它显然会让它大失所望,因为从不完整的类型派生是被禁止的

我真的没有看到这里的问题(当然除了错误消息)


有人能开导我吗?

哈!使用谷歌搜索我的问题对我没有帮助,但stackoverflow中的“相关问题”选项卡对我有帮助;)

作为参考,解决方案如下:

在头文件中,如果只有指向类的指针,则应该

  • 上课前(我以前就是这么做的),比如

    另一类

    在base.h和derived.h中,以及

    类派生

    在另一个班级。h,但是

  • 不要包含相应的头文件。只将它们包含在它们的.cpp文件中(这是我失败的地方)

  • 说明:由于指针总是具有相同的大小,并且它们的目标类型只有在您实际使用(即取消引用)它们时才相关,因此如果您告诉gcc存在标识符“派生的”(即predeclaration),gcc完全可以接受派生的*。事实上,如果您避免包含(自己的)头文件,而头文件的类型仅以这种方式使用(不需要完整),那么您就可以了