Exercice sur le sujet Polymorphismes
Transcription
Exercice sur le sujet Polymorphismes
Informatik 2 Objektorientiertes Programmieren mit C++ Exercice sur le sujet Polymorphismes: Écrivez un programme qui demande l'utilisateur de saisir n'importe quel nombres d'espèces animales. Après avoir saisi tous les animaux, les animaux sont afficher à la console avec son son spécifique en forme texte. Voici un exemple: Please choose an animal to add(c=Cat,d=Dog,f=Frog) Press <s> to display all animals c a cat has been added Please choose an animal to add(c=Cat,d=Dog,f=Frog) Press <s> to display all animals d a dog has been added Please choose an animal to add(c=Cat,d=Dog,f=Frog) Press <s> to display all animals f a frog has been added Please choose an animal to add(c=Cat,d=Dog,f=Frog) Press <s> to display all animals d a dog has been added Please choose an animal to add(c=Cat,d=Dog,f=Frog) Press <s> to display all animals s There are 4 animals in the zoo They say: I'am a cat Miau, Miau I'am a dog Wau, Wau I'am a frog Quak, Quak I'am a dog Wau, Wau Le programme doit être réaliser en utilisant le polymorphisme. Écrivez pour cela le code source selon le diagramme UML suivant : Informatik 2 Objektorientiertes Programmieren mit C++ Important: Les méthodes getSpecies et speak dans la classe de base Animal sont virtual! Voici le programme main() si vous ne voulez pas l’écrire vous même: int main() { vector<Animal*> animals; char input; do { cout << "Please choose an animal to add(c=Cat,d=Dog,f=Frog)" << endl; cout << "Press <s> to display all animals" << endl; input=_getche(); switch(input) { case 'c': animals.push_back(new Cat()); cout << "\na cat has been added\n" << endl; break; case 'd': animals.push_back(new Dog()); cout << "\na dog has been added\n" << endl; break; case 'f': animals.push_back(new Frog()); cout << "\na frog has been added\n" << endl; break; } }while(input!='s'); } cout << "\nThere are " << animals.size() << " animals in the zoo" << endl; cout << "They say:\n" << endl; for(int i=0;i<animals.size();i++) { cout << "I'am a " << animals[i]->getSpecies() << endl; animals[i]->speak(); cout << endl; } return 0; Informatik 2 Objektorientiertes Programmieren mit C++ Exercice supplémentaire Élargissez les classes de la façon qu'on peut donner de nom aux animaux: L'affichage d'un animal pourrait donc être comme suit: I'am a cat my name is Frida Miau, Miau