[英]C++ Polymorphism- find out type of derived class
I have a hierarchy of classes as follows: 我有一个类的层次结构,如下所示:
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)
{}
};
My problem: 我的问题:
All animals must reproduce, and they all do so the same way. 所有动物都必须繁殖,并且它们都以相同的方式繁殖。 In this example, I include only
rabbits
and wolves
, however I include more Animals
. 在此示例中,我仅包括
rabbits
和wolves
,但是我包括更多Animals
。
My question: 我的问题:
How can I modify ANIMAL::Reproduce()
to find out the type of animal on position field[x][y]
, and to call new()
on that particular type? 如何修改
ANIMAL::Reproduce()
以在位置field[x][y]
上找出动物的类型,并在该特定类型上调用new()
? (ie rabbit
would call new rabbit()
, wolf
would call new wolf()
) (即
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*/;
}
Define a pure virtual method, clone, in Animal: 在Animal中定义一个纯虚拟方法clone:
virtual Animal* clone () const = 0;
Then, a particular animal, like Rabbit, would define clone as follows: 然后,特定的动物(例如Rabbit)将如下定义克隆:
Rabbit* clone () const {
return new Rabbit(*this);}
Return types are covariant, so Rabbit*
is okay in Rabbit's definition. 返回类型是协变的,因此
Rabbit*
在Rabbit的定义中是可以的。 It doesn't have to be Animal*. 不必是动物*。
Do that for all animals. 对所有动物都这样做。
Then in reproduce, just call clone()
. 然后在复制中,只需调用
clone()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.