use*_*243 0 c++ polymorphism casting
我有一个类的层次结构如下:
class ANIMAL
{
public:
ANIMAL(...)
: ...
{
}
virtual ~ANIMAL()
{}
bool Reproduce(CELL field[40][30], int x, int y);
};
class HERBIVORE : public ANIMAL
{
public:
HERBIVORE(...)
: ANIMAL(...)
{}
};
class RABBIT : public HERBIVORE
{
public:
RABBIT()
: HERBIVORE(10, 45, 3, 25, 10, .50, 40)
{}
};
class CARNIVORE : public ANIMAL
{
public:
CARNIVORE(...)
: ANIMAL(...)
{}
};
class WOLF : public CARNIVORE
{
public:
WOLF()
: CARNIVORE(150, 200, 2, 50, 45, .40, 190, 40, 120)
{}
};
Run Code Online (Sandbox Code Playgroud)
我的问题:
所有动物都必须繁殖,它们都以同样的方式进行繁殖.在这个例子中,我只包括rabbits和wolves,但是我包括更多Animals.
我的问题:
如何修改ANIMAL::Reproduce()以找出位置上的动物类型field[x][y],并调用new()该特定类型?(即rabbit会打电话new rabbit(),wolf会打电话new wolf())
bool ANIMAL::Reproduce(CELL field[40][30], int x, int y)
{
//field[x][y] holds the animal that must reproduce
//find out what type of animal I am
//reproduce, spawn underneath me
field[x+1][y] = new /*rabbit/wolf/any animal I decide to make*/;
}
Run Code Online (Sandbox Code Playgroud)
在Animal中定义一个纯虚方法clone,:
virtual Animal* clone () const = 0;
Run Code Online (Sandbox Code Playgroud)
然后,像Rabbit一样的特定动物将按如下方式定义克隆:
Rabbit* clone () const {
return new Rabbit(*this);}
Run Code Online (Sandbox Code Playgroud)
返回类型是协变的,所以Rabbit*在Rabbit的定义中是可以的.它不一定是动物*.
对所有动物都这样做.
然后在重现,只需打电话clone().