关于C++虚函数的一点点~~

  Talk is cheap, show you the code:

1.(普通的)

 1 #include<cstdio>
 2 
 3 class B {
 4  public:
 5      void func() const {
 6          puts("B!");
 7      }
 8 };
 9 
10 class C : public B {
11  public:
12      void func() const {
13          puts("C!");
14      }
15 };
16 
17 void hehe(const B &b) {
18     b.func();
19 }
20 
21 int main() {
22     C c;
23     hehe(c);
24     return 0;
25 }

  运行结果:

  (应该是发生了向上转型什么的吧)

2. 基类的函数变为虚函数:

 1 #include<cstdio>
 2 
 3 class B {
 4  public:
 5      virtual void func() const {
 6          puts("B!");
 7      }
 8 };
 9 
10 class C : public B {
11  public:
12      void func() const {
13          puts("C!");
14      }
15 };
16 
17 void hehe(const B &b) {
18     b.func();
19 }
20 
21 int main() {
22     C c;
23     hehe(c);
24     return 0;
25 }

  运行结果:

  底层的原理暂时还不懂,有空再补充。

posted @ 2015-10-26 22:57  Newdawn_ALM  阅读(188)  评论(0)    收藏  举报