在另一个类C++的构造函数中实例化一个类的对象?
我正在写C++中的基本游戏,其中包含3个类:Game
类,Character
类和Item
类。在另一个类C++的构造函数中实例化一个类的对象?
Game
类将拥有游戏的所有逻辑,所以main
函数只会简单地创建Game object
,称其为逻辑函数,游戏将执行其他任何操作。可以有超过1名球员。
Character
类有一个可以容纳一个或多个Items的指针向量。一个角色可以有一个或多个项目
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
。
它是有道理的,但我无法弄清楚如何正确实施它。
这是我有 这是我到目前为止有:
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的构造函数中?
Depositphotos你的载入中出错地点。您需要将它们作为类成员移入类声明中,而不是作为构造函数中的局部变量。这些构造函数可以用填充这个载体(但是真的,做角色知道它们是什么样的“天生”的东西,而且游戏一开始就知道哪些角色是活着的?),但不应该声明他们。
试试这个:
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();
...
}
字符。ħ
#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;
}
感谢您的真棒回答,我没有期望收到像这样的详细答案。我想知道我是否必须将这些载体公诸于众?游戏的机制是当玩家开始时,他们将有机会用他自己选择的名字创建角色,然后将角色的物品添加到角色的库存 – 2013-05-03 08:37:35
不,这些矢量不需要公开。只需将其他方法添加到“Character”类中即可根据需要添加/删除/访问项目。 – 2013-05-03 15:10:49
你卡在哪里? – 2013-05-03 04:28:01
也许你的大部分逻辑都会进入你的[god object](https://en.wikipedia.org/wiki/God_object)'Game'。 – Zeta 2013-05-03 05:03:19
哦指针向量的原因基本上是cuz,这个游戏实际上是关于与物品交互(组合,匹配)。角色就像玩家的化身。这只是为了游戏编码的方式,它可以稍后扩展为具有多个角色(玩家) – 2013-05-03 05:10:55