我有如下的类层次结构:
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)
{}
};
我的问题:
所有动物都必须繁殖,而且它们的繁殖方式都是一样的。在这个例子中,我只包括了 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*/;
}
最佳答案
在Animal中定义一个纯虚方法clone:
virtual Animal* clone () const = 0;
然后,一个特定的动物,比如兔子,将如下定义克隆:
Rabbit* clone () const {
return new Rabbit(*this);}
返回类型是协变的,所以 Rabbit*
在 Rabbit 的定义中是可以的。它不一定是 Animal*。
对所有动物都这样做。
然后在重现中调用clone()
即可。
关于C++多态性——找出派生类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36684924/