6.4.5 Toán tử ép kiểu động (dynamic_cast) (1)
Hãy cùng phân tích source code bên dưới (đây là source code của chương trình ở trang trước nhưng đã được thay đổi) →
[…]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
#include <iostream> #include <string> using namespace std; class Pet { protected: string name; public: Pet(string name) : name(name) {} virtual void MakeSound(void) { cout << name << " is silent" << endl; } }; class Dog : public Pet { public: Dog(string name) : Pet(name) {} void MakeSound(void) { cout << name << " says: Woof!" << endl; } }; class GermanShepherd : public Dog { public: GermanShepherd(string name) : Dog(name) {} void MakeSound(void) { cout << name << " says: Wuff!" << endl; } void Laufen(void) { cout << name << " runs (gs)!" << endl; } }; class MastinEspanol : public Dog { public: MastinEspanol(string name) : Dog(name) {} void MakeSound(void) { cout << name << " says: Guau!" << endl; } void Ejecutar(void) { cout << name << " runs (mes)!" << endl; } }; void PlayWithPet(Pet *pet) { GermanShepherd *gs; MastinEspanol *mes; pet -> MakeSound(); if(gs = dynamic_cast<GermanShepherd *>(pet)) { gs -> Laufen(); } if(mes = dynamic_cast<MastinEspanol *>(pet)) { mes -> Ejecutar(); } } int main(void) { Pet *pet = new Pet("creature"); Dog *dog = new Dog("Dog"); GermanShepherd *gs = new GermanShepherd("Hund"); MastinEspanol *mes = new MastinEspanol("Perro"); PlayWithPet(pet); PlayWithPet(dog); PlayWithPet(gs); PlayWithPet(mes); return 0; } |