• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LyonLys
愿意在角落唱沙哑的歌 再大声也都是给你 请用心听 不要说话 Contact me via E-mail: lyon.lys@gmail.com
博客园    首页    新随笔    联系   管理    订阅  订阅

C++类继承中的虚方法

 

 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 }
View Code

 

 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 }
View Code

 

——written by Lyon

posted @ 2014-07-14 20:38  LyonLys  阅读(262)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3