简体   繁体   中英

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 .

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? (ie rabbit would call new rabbit() , wolf would call 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:

virtual Animal* clone () const = 0;

Then, a particular animal, like Rabbit, would define clone as follows:

Rabbit* clone () const {
    return new Rabbit(*this);}

Return types are covariant, so Rabbit* is okay in Rabbit's definition. It doesn't have to be Animal*.

Do that for all animals.

Then in reproduce, just call clone() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM