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

标签 c++ casting polymorphism

我有如下的类层次结构:

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 的定义中是可以的。它不一定是 Animal*。

对所有动物都这样做。

然后在重现中调用clone()即可。

关于C++多态性——找出派生类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36684924/

相关文章:

C++ 性能 : template vs boost. 任何

c++ - SendInput() 不等于在 C++ 键盘上手动按键?

C++11 线程队列

java - 从子类调用方法

c++ - 如何防止通过指向其父类型的指针删除对象?

haskell - 多态性:常数与函数

c# - 有关内存中转换的 C# 引用类型的信息

c++ - 基类指针,访问派生类成员变量?

objective-c - cocoa 中的 id 变量和类型转换

arrays - PowerShell:为什么一个参数上的 [Parameter(Mandatory = $True)] 会影响另一个参数的类型转换行为?