我试图完成一些事情,但我不确定它是否可能。
快速的想法是,我正在编写一个游戏并希望拥有一个不同怪物的单个阵列(或矢量)。继承主类Monster的每个类都会简单地覆盖它的功能(但不添加任何新功能)。
然后,当我查看怪物列表时,我可以调用它们所有的相同功能。
这里有一些代码可以显示我想要完成的任务:
class Monster
{
public:
int hp; //hit points
int atp; //attack power
int def; //defense
bool attacking;
bool defending;
virtual void attack();
virtual void defend();
};
void Monster::attack()
{}
void Monster::defend()
{}
class Goblin: public Monster
{
public:
virtual void attack() override;
virtual void defend() override;
};
void Goblin::attack()
{
//Goblin's attacking patterns
}
void Goblin::defend()
{
//Goblin's defending patterns
}
class Orc: public Monster
{
public:
virtual void attack() override;
virtual void defend() override;
};
void Orc::attack()
{
//Orc's attacking patterns
}
void Orc::defend()
{
//Orc's defending patterns
}
int main(void)
{
//This is where I'm not sure what to do:
//Initialize monsters. Make some Goblins, some Orcs
int num_monsters = 10;
Monster* monster_list;
monster_list = new Monster[num_monsters];
for (int i = 0; i < num_monsters; i++)
{
int which = rand() % 2;
switch (which)
{
case 0: //Goblin
monster_list[i] = new Goblin;
break;
case 1: //Orc
monster_list[i] = new Orc;
break;
}
}
bool quit = false;
while (quit == false)
{
for (int i = 0; i < num_monsters; i++)
{
if (monster_list[i].attacking == true)
monster_list[i].attack();
if (monster_list[i].defending == true)
monster_list[i].defend();
}
}
}
希望这说明了我想要做的事情。 我知道这不起作用,但我不确定如何使其发挥作用。 感谢您对此提出任何建议!
答案 0 :(得分:6)
您需要使用指向基类的指针向量。
std::vector<Monster*> monsters;
monsters.push_back(new FireDragon());
monsters.push_back(new IceDragon());
然后,您将能够遍历怪物矢量并调用常用方法。
for(auto monster = monsters.begin(); monster != monsters.end(); monster++)
{
(*monster)->attack();
}
课程:
class Monster {
public:
virtual ~Monster() {}
virtual void attack() = 0;
};
class FireDragon : public Monster {
public:
~FireDragon();
void attack()
{
std::cout << "Fire breath!" << std::endl;
}
};
class IceDragon : public Monster {
public:
~IceDragon();
void attack()
{
std::cout << "Ice breath!" << std::endl;
}
};
作为旁注,请务必在派生类或基类中创建虚拟析构函数。析构函数将被调用。
ETA:这是智能指针的实现:
/*
Use std::unique_ptr<Monster> if your implementation doesn't need to pass the
monster objects around
*/
std::vector<std::shared_ptr<Monster>> monsters;
/*
Use std::make_unique<FireDragon>() if using unique_ptr
*/
monsters.push_back(std::make_shared<FireDragon>());
monsters.push_back(std::make_shared<IceDragon>());
for(auto monster : monsters)
{
monster->attack();
}