This question already has answers here:
Resolve build errors due to circular dependency amongst classes
                                
                                    (11个答案)
                                
                        
                                去年关闭。
            
                    
我有2个具有循环依赖的类:

GameState.h

#include "Ball.h"

class GameState{
    Ball ball;
public:
    //...
    void groundTouched();
};




#include "GameState.h"

class Ball{
public:
    //...
    void update(GameState* gameState);
};


球cpp

#include "Ball.h"

void Ball::update(GameState* gameState){
    gameState->groundTouched();
}


当然我有类似的错误:

Ball.h:34:69: error: ‘GameState’ has not been declared


然后我在那里使用了前向声明:

class GameState;
class Ball{
public:
    //...
    void update(GameState* gameState);
};


但是有一个错误:

Ball.cpp:51:22: error: invalid use of incomplete type ‘class GameState’


如何从Ball调用GameState方法?可能吗?我知道我可以从Ball中删除GameState.h并从GameState中进行类似ball.isGroundTouched()的操作,但是对我而言,第一种选择看起来更面向对象且更受青睐。

最佳答案

您仍必须在源文件GameState.h中包含Ball.cpp头文件。

关于c++ - 无效使用不完整类型的循环依赖C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51245743/

10-11 23:16