1 #include <bits/stdc++.h> 2 using namespace std; 3 4 class A { 5 public: 6 void Show() { 7 cout << "A" << endl; 8 } 9 } ; 10 11 class B : public A { 12 public: 13 virtual void Show() { 14 cout << "B" << endl; 15 } 16 } ; 17 18 class C : public B { 19 public: 20 void Show() { 21 cout << "C" << endl; 22 } 23 } ; 24 25 int main() { 26 A a; B b; C c; 27 A &s1 = b; A &s2 = c; 28 B &t1 = b; B &t2 = c; 29 s1.Show(); s2.Show(); 30 t1.Show(); t2.Show(); 31 return 0; 32 }
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 class A { 5 public: 6 virtual void Show() { // 将virtual去掉运行做对比 7 cout << "A" << endl; 8 } 9 } ; 10 11 class B : public A { 12 public: 13 virtual void Show() { 14 cout << "B" << endl; 15 } 16 } ; 17 18 class C : public A { 19 public: 20 void Show() { 21 cout << "C" << endl; 22 } 23 } ; 24 25 class D : public A { 26 } ; 27 28 int main() { 29 ios::sync_with_stdio(0); 30 A a; B b; C c; D d; 31 A &t1 = a; A &t2 = b; A &t3 = c; A &t4 = d; 32 t1.Show(); t2.Show(); t3.Show(); t4.Show(); 33 a.Show(); b.Show(); c.Show(); d.Show(); 34 return 0; 35 }
——written by Lyon