2012-01-29 50 views
3

我目前正在尝试制作RPG游戏,并且遇到了一些麻烦。这是我迄今为止的布局。我应该如何为我的程序设置我的包含布局?

类:

  • 演员 - 基本类任何“存在”,如单位,弹丸等
  • 单位 - 继承演员,各单位依据。
  • 游戏 - 它只会有一个实例,它会包含指向游戏中所有对象的指针。我打算每隔0.1秒就对所有演员调用一个虚函数gameTick。

我遇到的问题是我想让所有的Actor都有一个指向Game实例的指针。如果我想要一个能够造成500半径范围伤害的咒语,我想让Game找到并返回该范围内的所有单位指针。

我的问题是,如果我在演员的头文件中包含游戏我的程序将无法编译。我如何让我的演员能够访问游戏?或者我正在以这种错误的方式去做?

在此先感谢。

// START main.cpp 

#include <iostream> 
#include "game.h" 

int main() 
{ 
    std::cout << "All done\n"; 

    return 0; 
} 

// END main.cpp 



// START actor.h 

#ifndef __ACTOR_H_ 
#define __ACTOR_H_ 

#include <iostream> 

//#include "game.h" Causes many errors if uncommented 

class Actor 
{ 
public: 
    Actor(); 

    std::string name_; 
}; 

#endif 

// END actor.h 



// START actor.cpp 

#include "actor.h" 

Actor::Actor() 
{ 
    name_ = "Actor class"; 
} 
// END actor.cpp 



// START unit.h 

#ifndef __UNIT_H_ 
#define __UNIT_H_ 

#include "actor.h" 

class Unit : public Actor 
{ 
public: 
    Unit(); 
}; 

#endif 

// END unit.h 



// START unit.cpp 

#include "unit.h" 

Unit::Unit() 
{ 
    name_ = "Unit class"; 
} 

// END unit.cpp 



// START game.h 

#ifndef __GAME_H_ 
#define __GAME_H_ 

#include <vector> 

#include "unit.h" 

class Game 
{ 
public: 
    std::vector< Actor * > actors_; 
    std::vector< Unit * > units_; 
}; 

#endif 

// END game.h 
+0

想要将某些事情分解为接口来修复依赖关系问题呢?我假设你得到的错误与循环依赖关系有关。 – 2012-01-29 04:45:48

+0

unit.h包含actor.h,actor.h包含game.h,game.h包含unit.h / – Dan 2012-01-29 04:46:48

回答

2

而不是做的:

#include "actor.h" 
#include "unit.h" 

你可以简单地向前声明两类:既然你只使用指针

class Actor; 
class Unit; 

,编译器只需要知道type是一个类,它不需要知道其他任何东西。现在在cpp文件中,您需要执行#include s

1

前向声明可能足以满足您的需要。当FWD声明是不够的唯一情况是

  • ,如果您有实例化的类的对象:编译器需要知道如何该对象已被修建
  • ,如果你需要访问的公共方法/这个类的属性:编译器需要知道这些方法是如何工作的或者你试图访问什么类型的属性。

如果您没有进行上述任何一项操作,那么前向声明就足够了。

相关问题