6.2.5 Tương thích kiểu – quay lại với Pet
Chúng ta đã sử dụng toán tử static_cast để cho phép Pets của chúng ta phát ra tiếng kêu của chúng. Đây là cách nó […]
|
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 |
#include <iostream> #include <string> using namespace std; class Pet { protected: string Name; public: Pet(string n) { Name = n; } void Run(void) { cout << Name << ": I'm running" << endl; } }; class Dog : public Pet { public: Dog(string n) : Pet(n) {}; void MakeSound(void) { cout << Name << ": Woof! Woof!" << endl; } }; class Cat : public Pet { public: Cat(string n) : Pet(n) {}; void MakeSound(void) { cout << Name << ": Meow! Meow!" << endl; } }; int main(void) { Pet *a_pet1 = new Cat("Tom"); Pet *a_pet2 = new Dog("Spike"); a_pet1 -> Run(); // 'a_pet1 -> MakeSound();' is not allowed here! a_pet2 -> Run(); // 'a_pet2 -> MakeSound();' is not allowed here! return 0; } |
|
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 |
#include <iostream> using namespace std; class Super { protected: int storage; public: void put(int val) { storage = val; } int get(void) { return storage; } }; class Sub : public Super { public: void print(void) { cout << "storage = " << storage << endl; } }; int main(void) { Sub object; object.put(100); object.put(object.get() + 1); object.print(); return 0; } |
Copyright © 2026 CppDeveloper by Phạm Minh Tuấn (SHUN)