![](/img/trans.png)
[英]C++ Polymorphism- call derived class method with different signature
[英]C++ Polymorphism- find out type of derived class
我有一个类的层次结构,如下所示:
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)将如下定义克隆:
Rabbit* clone () const {
return new Rabbit(*this);}
返回类型是协变的,因此Rabbit*
在Rabbit的定义中是可以的。 不必是动物*。
对所有动物都这样做。
然后在复制中,只需调用clone()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.