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*/;
}