在c++的另一个类的构造函数中实例化一个类的对象

Instantiate an object of one class in the constructor of another class C++?

本文关键字:一个 对象 c++ 另一个 构造函数 实例化      更新时间:2023-10-16

我正在用c++写一个基本的游戏,它有3个类:Game类,Character类和Item类。

Game类将具有游戏的所有逻辑,因此main函数将简单地创建Game object,调用其逻辑函数,游戏将执行其他所有操作。可以有不止一个玩家。

Character类有一个指针向量,可以保存一个或多个item。一个字符可以有一个或多个项目

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

我被游戏结构设计困住了。有人建议我在创建Game object时,同时创建Character object,然后角色对象将创建包含道具和Item object的指针向量。所以它喜欢当我调用constructor of the Game class时,它会调用constructor of the Character class,字符类的构造函数会自动调用constructor of the Item class

这很有意义,但是我不知道如何正确地实现它。

这就是我得到的这是我目前所看到的:

Game.cpp

Game::Game()
{
        vector<Character*> characterVector; //to hold Characters
}
Game::startLogic()
{
    string name;
    Character character = new Character(name);
}

Character.cpp

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

Item.cpp

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

main.cpp

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

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

你的向量在错误的地方。您需要将它们作为类成员移动到类声明中,而不是作为构造函数中的局部变量。构造函数可以填充向量(但实际上,角色知道他们"出生"的道具是什么吗?游戏知道什么角色在游戏一开始就活着吗?),但不应该声明向量。

试试这个:

Game.h

#include <vector>
class Character;
class Game
{
public:
    std::vector<Character*> characters;
    Game();
    ~Game();
    void startLogic();
};

Game.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();
    ...
}

Character.h

#include <string>
#include <vector>
class Item;
class Character
{
public:
    std::string name;
    std::vector<Item*> items;
    Character(std::string aName);
    ~Character();
};

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;
    }
}

Item.h

class Item
{
public:
    Item();
};

Item.cpp

#include "Item.h"
Item::Item()
{ //initialise all the attributes of an item 
}

main.cpp

int main()
{
    Game g;
    g.startLogic();
    return 0;
}
相关文章: