我之前的问题问错了,所以我会把它贴出来修复。
我有这个例子投掷expected class-name before ‘{’ token
编译时出错。我明白为什么它会失败,但我不知道如何解决它。谢谢。
BaseClass.h
#ifndef INHERITTEST_BASECLASS_H
#define INHERITTEST_BASECLASS_H
#include "ElementClass.h"
class ElementClass;
class BaseClass
{
private:
ElementClass *m_someField;
};
#endif
元素类.h
#ifndef INHERITTEST_ELEMENTCLASS_H
#define INHERITTEST_ELEMENTCLASS_H
#include "ChildClass.h"
class ChildClass;
class ElementClass
{
private:
ChildClass *m_class;
};
#endif
儿童班
#ifndef INHERITTEST_CHILDCLASS_H
#define INHERITTEST_CHILDCLASS_H
#include "BaseClass.h"
class ChildClass : public BaseClass
{
};
#endif
你有循环依赖的 .h 文件。
在 BaseClass.h 中:
#ifndef INHERITTEST_BASECLASS_H
#define INHERITTEST_BASECLASS_H
#include "ElementClass.h" // Includes ElementClass.h
在 ElementClass.h 中:
#ifndef INHERITTEST_ELEMENTCLASS_H
#define INHERITTEST_ELEMENTCLASS_H
#include "ChildClass.h" // Which included BaseClass.h
您可以删除这些#include
行,因为您仅通过指针使用这些类,并且前向声明足以达到此目的。
使用
继承时,以下内容
#include "ChildClass.h"
class ChildClass;
是不必要的,如果您要将它们分解为单独的源文件(看起来像您是),您可以说
#include "ElementClass.h"
在派生类的源文件中