gpt4 book ai didi

c++ - 我应该如何为我的程序设置我的包含布局?

转载 作者:太空狗 更新时间:2023-10-29 21:27:27 25 4
gpt4 key购买 nike

我目前正在尝试制作一款角色扮演游戏,但遇到了一些麻烦。这是我目前的布局。

类:

  • Actor - 任何“存在”的东西的基类,例如单位、射弹等。
  • Unit - 继承 Actor,所有单元的基础。
  • 游戏 - 它只有一个实例,并且包含指向游戏中所有对象的指针。我计划让它每 0.1 秒对所有 Actor 调用一个虚函数 gameTick。

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

我的问题是,如果我在 Actor 的头文件中包含 Game,我的程序将无法编译。我怎样才能让我的 Actor 访问游戏?还是我的做法有误?

提前致谢。

// 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

最佳答案

而不是做:

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

您可以简单地转发声明这两个类:

class Actor;
class Unit;

因为你只使用指针,编译器只需要知道类型是一个类,它不需要知道任何其他信息。现在在 cpp 文件中,您需要执行 #includes

关于c++ - 我应该如何为我的程序设置我的包含布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9050947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com