最近在我的代码中遇到了一些问题,围绕着我现在所知道的循环依赖项。简而言之,有两个类,球员和球,它们都需要使用来自另一个的信息。在代码中的某个时刻,两者都将传递另一个的引用(来自另一个包含两个 .h 文件的类)。
阅读后,我从每个文件中删除了 #include.h 文件,并使用了前向声明。这解决了能够相互声明类的问题,但是我现在在尝试访问对对象的传递引用时留下了"不完整的类型错误"。似乎有一些类似的例子,尽管经常与更复杂的代码混合在一起,并且很难缩小到基础知识。
我以最简单的形式(本质上是一个骨架)重写了代码。
球:
class Player;
class Ball {
public:
Player& PlayerB;
float ballPosX = 800;
private:
};
玩家.h:
class Ball;
class Player {
public:
void doSomething(Ball& ball);
private:
};
播放器.cpp:
#include "Player.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
任何帮助理解为什么会这样,将不胜感激:)
此顺序放置定义,则将编译代码
class Ball;
class Player {
public:
void doSomething(Ball& ball);
private:
};
class Ball {
public:
Player& PlayerB;
float ballPosX = 800;
private:
};
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
int main()
{
}
函数 doSomething 的定义需要类 Ball 的完整定义,因为它访问其数据成员。
在代码示例模块 Player 中.cpp 无法访问类 Ball 的定义,因此编译器发出错误。
Player.cpp
需要Ball
类的定义。因此,只需添加#include "Ball.h"
播放器.cpp:
#include "Player.h"
#include "Ball.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
这是我所拥有的以及导致我的"不完整类型错误"的原因:
#include "X.h" // another already declared class
class Big {...} // full declaration of class A
class Small : Big {
Small() {}
Small(X); // line 6
}
//.... all other stuff
我在文件"Big.cpp"中所做的,我用 X 作为参数声明了 A2 的构造函数是......
大.cpp
Small::Big(X my_x) { // line 9 <--- LOOK at this !
}
我写了"小::大"而不是"小::小",多么愚蠢的错误。我一直收到 X 类的错误"现在允许不完整的类型"(在第 6 行和第 9 行中),这完全令人困惑。
无论如何,这就是可能发生错误的地方,主要原因是我在编写它时很累,我需要 2 个小时的探索和重写代码才能揭示它。
就我而言,这是因为错字。
我有类似的东西
struct SomethingStrcut { /* stuff */ };
typedef struct SomethingStruct smth;
请注意,结构的名称与类型定义的名称不同。
我把struct
拼错了strcut
.
查看您的代码,看看您是否有一些拼写错误。