C++多态性-找出派生类的类型

C++ Polymorphism- find out type of derived class

本文关键字:类型 派生 多态性 C++      更新时间:2023-10-16

我有如下的类层次结构:

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)
    {}
};

我的问题:

所有的动物都必须繁殖,而且它们都以同样的方式繁殖。在这个例子中,我只包括rabbitswolves,但是我包括更多的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的定义中是可以的。它不一定是动物。

对所有动物都这样做。

然后在重放中,只需调用clone()