2016-04-18 3 views
0

Ich habe eine Hierarchie von Klassen wie folgt:C++ Polymorphism- herauszufinden Art der abgeleiteten Klasse

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) 
    {} 
}; 

Mein Problem:

Alle Tiere reproduzieren müssen, und sie alle tun so auf die gleiche Weise . In diesem Beispiel schließe ich nur rabbits und wolves ein, jedoch schließe ich mehr Animals ein.

Meine Frage:

Wie kann ich ANIMAL::Reproduce() ändern auf Position, um die Art des Tieres, um herauszufinden, field[x][y] und new() auf diesen bestimmten Typ zu nennen? (Dh rabbit würde new rabbit() nennen, würde wolfnew wolf() nennen)

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

Antwort

6

definiert eine rein virtuelle Methode, Klon, in Tiere:

virtual Animal* clone() const = 0; 

dann ein bestimmtes Tier, wie Kaninchen, würde definieren Klons als folgt:

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

Return Typen covariant sind, so Rabbit* ist in Kaninchen ist in Ordnung Definition. Es muss nicht Animal * sein.

Tun Sie das für alle Tiere.

Dann in reproduzieren, rufen Sie einfach clone().