例如,我想创建一个游戏,它有一个GameFlow来控制游戏事件流,我也有一些控制器(例如:PlayerAttackController,EnnemyControllerController)用于不同的流程。
GameFlow用于切换控制器,控制器通知GameFlow改变状态:
简化代码我不使用.cpp并仅使用公共属性:
GameFlow.h
class GameFlow{
public:
int state;
IController* controller;
void changeState(){
if(controller!=NULL){
delete controller;
}
if(state==0){
controller=new PlayerAttackController();
controller->gameFlow=this;
}else if(state==1){
controller=new EnemyAttackController();
controller->gameFlow=this;
}
.
.
.
}
};
IController.h
class IController{
};
PlayerAttackController.h
class PlayerAttackController : public IController{
public:
GameFlow* gameFlow;
void buttonPressed(){
//some player attack code
.
.
.
gameFlow->state=1;
gameFlow->changeState();
}
};
(其他控制器类似)
现在很明显GameFlow包含Controller,每个控制器都包含GameFlow,有没有什么方法可以打破GameFlow和Controller之间的循环依赖?
答案 0 :(得分:2)
不要在类中定义您的成员函数。相反,在类中声明它们(只告诉它们存在的编译器)并在之后定义它们(可能在每个类的.cpp文件中,尽管这不是唯一可能的布局)。
在GameFlow.h中:
class GameFlow{
public:
int state;
IController* controller;
void changeState(); // this is a declaration
};
在GameFlow.cpp中,包含GameFlow.h和PlayerAttackController.h,然后:
// this is a definition
void GameFlow::changeState()
{
if(controller!=NULL){
delete controller;
}
if(state==0){
controller=new PlayerAttackController();
controller->gameFlow=this;
}else if(state==1){
controller=new EnemyAttackController();
controller->gameFlow=this;
}
.
.
.
}
PlayerAttackController也是如此。在PlayerAttackController.h中:
class PlayerAttackController : public IController{
public:
GameFlow* gameFlow;
void buttonPressed(); // this is a declaration
};
在PlayerAttackController.cpp中,包括两个标题和:
// this is a definition
void PlayerAttackController::buttonPressed(){
//some player attack code
.
.
.
gameFlow->state=1;
gameFlow->changeState();
}
您还希望出于其他原因在.cpp文件中定义您的函数 - 编译时间很长。