[英]c++ “Incomplete type not allowed” error accessing class reference information (Circular dependency with forward declaration)
最近我的代码中有一些问题围绕着我现在所知的循环依赖。 简而言之,有两个类,Player 和 Ball,它们都需要使用来自另一个的信息。 在代码中的某个点,将传递另一个的引用(来自将包含两个 .h 文件的另一个类)。
在阅读完之后,我从每个文件中删除了 #include.h 文件并进行了前向声明。 这解决了能够在彼此中声明类的问题,但是当我尝试访问传递的对象引用时,我现在遇到了“不完整的类型错误”。 周围似乎有一些类似的示例,但通常与更复杂的代码混合在一起,并且很难缩小到基础知识。
我已经以最简单的形式(本质上是一个骨架)重写了代码。
球.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 的构造函数是..
Small::Big(X my_x) { // line 9 <--- LOOK at this !
}
我写了 "Small::Big" 而不是 "Small::Small" ,这是一个多么愚蠢的错误......我一直收到类 X 的错误“现在允许不完整的类型”(在第 6 行和第 9 行),完全混乱..
无论如何,这是可能发生错误的地方,主要原因是我写它时很累,我需要2个小时的探索和重写代码才能揭示它。
就我而言,这是因为打字错误。
我有类似的东西
struct SomethingStrcut { /* stuff */ };
typedef struct SomethingStruct smth;
请注意结构的名称与类型定义的名称不同。
我将struct
拼错为strcut
。
查看您的代码,看看您是否有一些拼写错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.