C++类相互引用( => 错误 + 字段"..."类型不完整)
C++ classes refer to each other ( => error + field '...' has incomplete type)
我的应用程序中的类是这样工作的:Creature
与Action
s有几个字段。当这些Action
必须运行时,Creature
调用someActionField->do(this)
。Action有方法viod do(Creature* cr)
以及关于如何使用该Creature
的所有信息。
所以,生物必须有Action
字段,并且知道Action
有do
方法。Action必须知道Creature
有这样的字段:Will, HP等…
我有
creature.h
#include "effect.h"
#include "heedupdate.h"
namespace Core
{
class Action;
class Creature : public NeedUpDate
{
public:
virtual ~Creature();
int HP;
Action onHit;
Action onDie;
// ...
};
}
#endif
和action.h
#include "creature.h"
namespace Core
{
class Action
{
public:
Action();
virtual void _do(Creature* cr);
virtual ~Action();
};
但是在这种情况下出现`onDie' has incomplete type
字段错误。如果我将action.h包含到creature.h中,我将使用文件"优先"
您的Creature
类有类型为Action
的成员。编译器需要知道Action
类的完整定义才能编译它——由前向声明生成的不完整类型是不够的。
Action
类只需要一个指向该头文件中Creature
对象的指针。在这种情况下,编译器只需要知道Creature
将在某个时刻被定义。
在你的特殊情况下,你可以改变你声明类的顺序。
(即。
action.h
中前声明Creature
,在creature.h
中包含action.h
)in action.h put class Creature;
and #include "action.h"
对于指针,你不需要完整的定义,因为它只是一个指针,编译器可以为它生成"代码"。如果你使用一个简单的类/结构,编译器必须知道它的类型,因为它需要知道它的大小。
当正向声明一个类型时,编译器只知道这个类型存在;它不知道它的大小、成员或方法,因此称为不完全类型
不能使用不完整类型来声明成员(因为编译器在声明时需要知道类型的大小),因此会得到错误。
你不需要在action.h中#include " Creature. h",但你只需要转发声明类Creature。你需要在creature.h
中#include "action.h"你的头文件应该有以下结构:
creature.h
#include "effect.h"
#include "action.h"
#include "heedupdate.h"
action.h
class creature;
这使用了两个规则:
- 可以声明接受/返回不完整类型的函数或方法:
action.h
只声明了一个接受不完整类型(Creature)的函数
- 不能声明不完整类型的成员。
creature.h
必须包含action.h
,因为它声明了Action
类型的成员。
你不需要在action.h中#include "creature.h"。您所需要的只是向前声明类Creature。你需要在creature.h中#include " Action. h",因为onHit和onDie都是Action的实例。
使用引用或指针:
#include "effect.h"
#include "heedupdate.h"
namespace Core
{
class Action;
class Creature : public NeedUpDate
{
public:
virtual ~Creature();
int HP;
Action & onHit;
Action & onDie;
// ...
};
}
#endif
这样你就可以打破依赖关系,而不需要一个完全声明的Action
类
- 将结构字段的类型展开为可变模板参数
- 结构体和类的不同大小(),彼此具有相同的字段类型
- 错误:字段'dateOfBirth'的类型不完整'Poco::Data::Date'
- 获取具有字段名称的 SELECT 字段类型,并带有 MariaDB C++连接器
- 无法初始化以 std::byte 作为成员类型的位字段
- 无法访问 Arduino 结构字段。错误"退出状态 1。xxxx 不命名类型"
- 在这种情况下,如何从类型 "const char*" 初始化字段?
- 确定输入"conscalc: calc"的类型时出错。不能联合编码器。具有不同字段集的结构类型
- 字段在正向声明中具有不完整的类型
- 使用固定大小类型时强制对位字段(C++14 之前)进行签名
- 返回对位字段的访问类型
- 将枚举类型保存在位字段 [dcl.enum] [class.bit] 中
- 将指向结构的指针转换为具有较少字段数的另一种结构类型
- 位字段成员的类型
- 如何从提升属性树中读取字段类型
- 字段名称与使用未命名命名空间的字段类型相同
- 字段类型不完整
- "位字段类型对于位数来说太小"错误是否属于C++标准?
- C++类相互引用( => 错误 + 字段"..."类型不完整)
- 头文件-不完整的字段类型c++