nat*_*828 31 c++ reference class forward-declaration
最近我的代码中有一些问题围绕着我现在所知的循环依赖.简而言之,有两个类,Player和Ball,它们都需要使用另一个类的信息.代码中的某些位置都会传递另一个引用(来自另一个包含两个.h文件的类).
在阅读完之后,我从每个文件中删除了#include.h文件并进行了前向声明.这解决了能够在彼此中声明类的问题,但是当我尝试访问对象的传递引用时,我现在留下了"不完整类型错误".似乎有一些类似的例子,虽然经常混合更复杂的代码,很难缩小到基础.
我已经用最简单的形式(基本上是一个骨架)重写了代码.
Ball.h:
class Player;
class Ball {
public:
Player& PlayerB;
float ballPosX = 800;
private:
};
Run Code Online (Sandbox Code Playgroud)
Player.h:
class Ball;
class Player {
public:
void doSomething(Ball& ball);
private:
};
Run Code Online (Sandbox Code Playgroud)
Player.cpp:
#include "Player.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
Run Code Online (Sandbox Code Playgroud)
任何帮助理解为什么会这样的情况将不胜感激:)
娜塔莉
Vla*_*cow 20
如果您将按此顺序放置定义,则将编译代码
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()
{
}
Run Code Online (Sandbox Code Playgroud)
函数doSomething的定义需要Ball类的完整定义,因为它访问其数据成员.
在您的代码示例模块中,Player.cpp无法访问类Ball的定义,因此编译器会发出错误.
Nim*_*ush 15
Player.cpp
需要定义Ball
类.所以简单地添加#include "Ball.h"
Player.cpp:
#include "Player.h"
#include "Ball.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
Run Code Online (Sandbox Code Playgroud)