0
類
的我的類層次結構如下:C++ 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)
{}
};
我的問題:
所有的動物都必須複製,他們都這樣做同樣的方式。在這個例子中,我只包括rabbits
和wolves
,但是我包含更多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*/;
}