
6.4.3 Truyền vào một đối tượng của lớp dẫn xuất (1)
Bây giờ sẽ là một hệ thống phân lớp phức tạp hơn một chút →
Chúng ta có thể minh họa cấu trúc của
[…]
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 |
#include <iostream> #include <string> using namespace std; class Pet { protected: string name; public: Pet(string name) { this -> name = name; } 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; } }; class MastinEspanol : public Dog { public: MastinEspanol(string name) : Dog(name) {} void MakeSound(void) { cout << name << " says: Guau!" << endl; } }; void PlayWithPet(Pet &pet) { pet.MakeSound(); } int main(void) { Pet pet("creature"); Dog dog("Dog"); GermanShepherd gs("Hund"); MastinEspanol mes("Perro"); PlayWithPet(pet); PlayWithPet(dog); PlayWithPet(gs); PlayWithPet(mes); return 0; } |