2016-04-18 31 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()