2016-04-18 17 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が含まれています。

私の質問:

どのように私は位置field[x][y]上の動物の種類を見つけるためにANIMAL::Reproduce()を変更することができ、その特定のタイプにnew()を呼び出すこと?動物では、クローン、

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

は純粋仮想メソッドを定義します(つまり、rabbitnew rabbit()を呼ぶだろう、wolfnew wolf()を呼ぶだろう):

virtual Animal* clone() const = 0; 

を次に、特定の動物を、ウサギ等のクローンを定義します次の:

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

戻り値の型は共変なので、Rabbit*はうさぎさんで大丈夫です定義。それは動物*である必要はありません。

これはすべての動物で行います。

次に再生するには、clone()に電話してください。

関連する問題