2016-04-18 30 views
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) 
    {} 
}; 

我的问题:

所有的动物都必须复制,他们都这样做同样的方式。在这个例子中,我只包括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*/; 
} 

回答

6

定义一个纯虚拟方法,克隆,在动物:

virtual Animal* clone() const = 0; 

然后,特定动物,如兔子,将定义克隆作为如下:

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

返回类型是协变的,所以Rabbit*是好的兔的定义。它不一定是Animal *。

对所有动物都这样做。

然后重现,只需拨打clone()