我该如何为我的程序设置包含的布局?

时间:2012-01-29 04:27:06

标签: c++ header-files

我目前正在尝试制作RPG游戏,但我遇到了一些麻烦。这是我到目前为止的布局。

类:

  • 演员 - 任何“存在”的基类,如单位,射弹等。
  • 单位 - 继承Actor,所有单位的基础。
  • 游戏 - 它只有一个实例,它将包含指向游戏中所有对象的指针。我计划每隔0.1秒让所有演员称之为虚拟功能gameTick。

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

我的问题是如果我在Actor的头文件中包含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

2 个答案:

答案 0 :(得分:2)

而不是:

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

你可以简单地向前声明两个类:

class Actor;
class Unit;

由于你只使用指针,编译器只需要知道类型是一个类,它不需要知道其他任何东西。现在在cpp文件中,您需要执行#include s

答案 1 :(得分:1)

前瞻性声明可能足以满足您的目的。当前一个声明不够时,唯一的情况是

  • 如果你必须实例化一个类的对象:编译器需要知道如何构造该对象
  • 如果您需要访问该类的公共方法/属性:编译器需要知道这些方法的工作方式或您尝试访问的属性类型。

如果你没有做上述任何一项,那么前向声明就足够了。