我目前正在尝试制作RPG游戏,但我遇到了一些麻烦。这是我到目前为止的布局。
类:
我遇到的问题是我希望所有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
答案 0 :(得分:2)
而不是:
#include "actor.h"
#include "unit.h"
你可以简单地向前声明两个类:
class Actor;
class Unit;
由于你只使用指针,编译器只需要知道类型是一个类,它不需要知道其他任何东西。现在在cpp文件中,您需要执行#include
s
答案 1 :(得分:1)
前瞻性声明可能足以满足您的目的。当前一个声明不够时,唯一的情况是
如果你没有做上述任何一项,那么前向声明就足够了。