如何在 c++ 中动态创建(游戏角色)类的多个对象



我必须修改我的程序并创建一个新的(Gamefigures)类,我当前的类(Rabbit和Hedg)从中继承。代码是一个小游戏,两只动物比赛直到达到目标,但在第二个任务中,我必须确保这些动物的多次迭代可以比赛。(例如 5 对 5 或 X 对 X)。我可以将一些变量或方法移动到Gamefigures类中。两种动物都使用不同的规则来行走。如何创建一个新类,该类动态创建同一类的多个对象,我的当前类从中继承?

我尝试使用新表达式创建一个新对象,但我不知道这是否是正确的做法。

我试过了:

Hedg* nHedg = new Hedg[numFigures];

这是我的其余代码:

class Hedg: public Gamefigures
{
private:
int salat = 1;
protected:
int position1 = 0;
public:
bool turn(int fields)
{
int counter = 10;
if (fields < 11)//Less than 10 fields
{
while ((counter > 0))
{
if (counter < fields)//max 10 fields
{
fields = counter;
}
position1 += fields;//walk
counter -= fields;
if (counter <= 0)
{
salat = 0;
}
}
getSalat();
return true;
}
else
return false;
}
Hedg()
{
}
int getPosition1()
{
return position1;
}
int getSalat()
{
return salat = 1;
}
int getStock1()
{
return salat;
}
~Hedg()
{
}
};
class Game :public Hedg, public Rabbit
{
private:
int goal = 0;
int numFields = 0;
protected:
Rabbit theRabbit;
Hedg theHedg;
public:
Game();
Game(int numFields);
int getGoal();
int dice();
void doyourturn();
bool getStand();
~Game();
};

以下是错误消息:

Error code C4430 missing typespecifier

我认为多态性是你的用例所需要的,它将解决你的问题。

假设您有一个动物的基类:

class Animal
{
// ...
// Create all the (pure) virtual methods to be redefined by a derived class
virtual void walk() = 0; // For example
};

然后你定义你的两种特定的动物,兔子和刺猬:

class Rabbit : public Animal
{
// ...
// Redefine here the (pure) virtual methods of Animal for a Rabbit
void walk() override;
};
class HedgeHog : public Animal
{
// ...
// Redefine here the (pure) virtual methods of Animal for a HedgeHog
void walk override;
};

您可以使用多态性来处理您的动物列表:

std::vector<Animal*> race_competitors;
race_competitors.push_back(new Rabbit);
race_competitors.push_back(new HedgeHog);

这样,当您在竞争对手身上调用walk()方法时,它将自动执行相应动物的正确行走规则。

当然,在比赛结束时,不要忘记delete载体的内容,因为动物是用new创建的("手动"分配的内存,在堆上)。


仅供参考,Game类不必继承RabbitHedgeHog,它只需要知道他们是类成员,或者更好的是,将std::vector<Animal*>存储为竞争对手列表。

我希望它能帮助您改进设计并解决您的问题。

最新更新