虚函数的本质就是指针类型转换实现的结果

  1 /* 虚函数 */
  2 
  3 #include<iostream>
  4 
  5 using namespace std;
  6 
  7 class A
  8 {
  9 public:
 10     A(char x):x(x)
 11     {
 12     
 13     }
 14 
 15     void show()
 16     {
 17         cout << typeid(*this).name << " " << x << endl;
 18     }
 19 protected:
 20     char x;
 21 };
 22 
 23 class B : public A
 24 {
 25 public:
 26     B(char x,char y):A(x),y(y)
 27     {
 28         
 29     }
 30 
 31     void show()
 32     {
 33         cout << typeid(*this).name << " " << x << " " << y << endl;
 34     }
 35 protected:
 36     char y;
 37 };
 38 
 39 
 40 class C : public B
 41 {
 42 public:
 43     C(char a,char b,char c):B(a,b),z(c)
 44     {
 45 
 46     }
 47     void show()
 48     {
 49         cout << typeid(*this).name << " " << x << " " << y << " " << z << endl;
 50     }
 51 
 52 protected:
 53     char z
 54 };
 55 
 56 void main()
 57 {
 58 
 59 // 通过基类指针只能访问从基类继承的成员 
 60 
 61     A *p;
 62     A a('A');
 63     B b('B','C');
 64     C c('D','E','F');
 65 
 66     p = &a;
 67     p->show();
 68 
 69     p = &b;
 70     p->show();
 71 
 72     p = &c;
 73     p->show();
 74     
 75     p = &b;
 76     (static_cast<B*>(p))->show();// 类型转换,虚函数的底层机制之一 就是类型转换
 77 
 78     p = &c;
 79     (static_cast<C*>(p))->show();
 80     cin.get();
 81 }
 82 
 83 
 84 //----------------------------------------------------------------------------------
 85 
 86 #include<iostream>
 87 
 88 using namespace std;
 89 
 90 class A
 91 {
 92 public:
 93     A(char x):x(x)
 94     {
 95     
 96     }
 97 
 98     virtual void show()// 基类定义虚函数
 99     {
100         cout << typeid(*this).name << " " << x << endl;
101     }
102 protected:
103     char x;
104 };
105 
106 class B : public A
107 {
108 public:
109     B(char x,char y):A(x),y(y)
110     {
111         
112     }
113 
114     void show()
115     {
116         cout << typeid(*this).name << " " << x << " " << y << endl;
117     }
118 protected:
119     char y;
120 };
121 
122 
123 class C : public B
124 {
125 public:
126     C(char a,char b,char c):B(a,b),z(c)
127     {
128 
129     }
130     void show()
131     {
132         cout << typeid(*this).name << " " << x << " " << y << " " << z << endl;
133     }
134 
135 protected:
136     char z
137 };
138 void main()
139 {
140     A *p;
141     A a('A');
142     B b('B','C');
143     C c('D','E','F');
144 
145     p = &a;
146     p->show();
147 
148     p = &b;
149     p->show();
150 
151     p = &c;
152     p->show();
153 }

 

posted on 2015-06-10 09:19  Dragon-wuxl  阅读(94)  评论(0)    收藏  举报

导航