簡體   English   中英

在另一個C ++類的構造函數中實例化一個類的對象?

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

我正在用C ++編寫一個基本游戲,該游戲具有3個類: Game類, Character類和Item類。

Game類將具有Game所有邏輯,因此main函數將僅創建Game object ,調用其邏輯函數,然后游戲將執行其他所有操作。 可以有1位以上的玩家。

Character類具有一個可以容納一個或多個Item的指針向量。 一個角色可以有一個或多個物品

Item類具有Item所有屬性和功能。

我一直在設計游戲的結構。 有人建議我以這樣一種方式來構造游戲,即在創建Game object時,它還會創建一個Character object ,然后該Character對象將創建一個指針向量來保存Item和Item object 因此,就像當我調用constructor of the Game classconstructor of the Game class ,它將調用constructor of the Character class的構造函數,而Character類的constructor of the Item class將自動調用constructor of the Item classconstructor of the Item class

這是有道理的,但我不知道如何正確實施它。

這是我所擁有的這是我到目前為止所擁有的:

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

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();

    ...
}

字符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();
};

Item.cpp

#include "Item.h"

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

main.cpp

int main()
{
    Game g;
    g.startLogic();
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM