zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Linux常用操作命令总结
    Centos7安装FastDFS教程
    Permutation Sequence
    Next Permutation
    Remove Element
    4Sum
    3Sum Closest
    3Sum
    Longest Consecutive Sequence
    Median of Two Sorted Arrays
  • 原文地址:https://www.cnblogs.com/LyonLys/p/20140714_Lyon.html
Copyright © 2011-2022 走看看