0

我正在用 C++ 编写一个基本游戏,它具有 3 个类:Game类、Character类和Item类。

该类Game将具有游戏的所有逻辑,因此该main函数将只是简单地创建Game object,调用其逻辑函数,游戏将完成其他所有事情。可以有超过 1 个玩家。

该类Character有一个指针向量,可以容纳一个或多个项目。一个角色可以拥有一件或多件物品

该类Item具有项目的所有属性和功能。

我一直在设计游戏的结构。有人建议我以这样一种方式构建我的游戏,即在Game object创建 时,它还创建一个Character object,然后该 Character 对象将创建一个指针向量来保存 Item ,而Item object. 所以它喜欢当我调用 时constructor of the Game class,它会调用constructor of the Character class,并且 Character 类的构造函数会自动调用constructor of the Item class

这是有道理的,但我无法弄清楚如何正确实施它。

这就是我所拥有的这是我到目前为止所拥有的:

游戏.cpp

Game::Game()
{
        vector<Character*> characterVector; //to hold Characters
}

Game::startLogic()
{
    string name;
    Character character = new Character(name);
}

字符.cpp

Character::Character(string name)
{
    m_name = name;
    vector<Item*> itemVector;
}

项目.cpp

Item::Item()
{ //initialise all the attributes of an item 
}

主文件

void main()
{
    Game g;
    g.startLogic();
}

所以我可以在游戏运行时创建一个角色(尽管稍后我仍然必须将该角色推入 characterVector),但我不太确定如何为该角色创建项目。我的意思是我应该把那个实例化代码放在哪里?在 startLogic 函数中,在 Game 的构造函数中,还是在 Character 的构造函数中?

4

1 回答 1

1

你的向量在错误的地方。您需要将它们作为类成员移动到类声明中,而不是作为构造函数中的局部变量。构造函数可以填充向量(但实际上,角色是否知道他们“出生”时带有哪些物品,游戏是否知道游戏一开始哪些角色还活着?),但不应该声明它们。

试试这个:

游戏.h

#include <vector>

class Character;

class Game
{
public:
    std::vector<Character*> characters;

    Game();
    ~Game();
    void startLogic();
};

游戏.cpp

#include "Game.h"
#include "Character.h"
#include <memory>

Game::Game()
{
}

Game::~Game()
{
    for (std::vector<Character*>::iterator i = characters.begin();
        i != characters.end();
        ++i)
    {
        delete *i;
    }
}

Game::startLogic()
{
    ...

    // using auto_ptr as a safety catch in case of memory errors...

    std::auto_ptr<Character> c(new Character("Joe Smoe"));

    std::auto_ptr<Item> i(new Item);
    c->items.push_back(i.get());
    i.release();

    characters.push_back(c.get());
    c.release();

    ...
}

字符.h

#include <string>
#include <vector>

class Item;

class Character
{
public:
    std::string name;
    std::vector<Item*> items;

    Character(std::string aName);
    ~Character();
};

字符.cpp

#include "Character.h"
#include "Item.h"

Character::Character(std::string aName)
    : name(aName)
{
}

Character::~Character()
{
    for (std::vector<Item*>::iterator i = items.begin();
        i != items.end();
        ++i)
    {
        delete *i;
    }
}

项目.h

class Item
{
public:
    Item();
};

项目.cpp

#include "Item.h"

Item::Item()
{ //initialise all the attributes of an item 
}

主文件

int main()
{
    Game g;
    g.startLogic();
    return 0;
}
于 2013-05-03T05:20:20.730 回答