Ich habe eine Hierarchie von Klassen wie folgt:C++ Polymorphism- herauszufinden Art der abgeleiteten Klasse
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)
{}
};
Mein Problem:
Alle Tiere reproduzieren müssen, und sie alle tun so auf die gleiche Weise . In diesem Beispiel schließe ich nur rabbits
und wolves
ein, jedoch schließe ich mehr Animals
ein.
Meine Frage:
Wie kann ich ANIMAL::Reproduce()
ändern auf Position, um die Art des Tieres, um herauszufinden, field[x][y]
und new()
auf diesen bestimmten Typ zu nennen? (Dh rabbit
würde new rabbit()
nennen, würde wolf
new wolf()
nennen)
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*/;
}