zoukankan      html  css  js  c++  java
  • C++之虚基类

    C++中的继承关系容易导致二义性,但是使用虚基类能够避免二义性,其源码如下

     1 class Anamal{
     2 public:
     3     virtual void eat() = 0;
     4     virtual void sleep(){
     5         cout<<"ZZZZZZZZZZZZZ........"<<endl;
     6     }
     7 };
     8 class Dog:public virtual Anamal{
     9 public:
    10     virtual void eat(){
    11         cout<<"Dog eat food"<<endl;
    12     }
    13 };
    14 class Bird:public virtual Anamal{
    15 public:
    16     virtual void eat(){
    17         cout<<"Bird eat food"<<endl;
    18     }
    19 };
    20 
    21 class DogBird:public Dog,public Bird{
    22 public:
    23     virtual void eat(){
    24         Dog::eat();
    25     }
    26 };
    27 void main(int argc, char **argv)
    28 {
    29     DogBird db;
    30     db.eat();
    31     db.sleep();
    32 }
    View Code

    其中调用sleep的方法中就避免了二义性,如果不是用虚基类则当调用sleep方法时,就不知道到底是调用子类Dog还是子类Bird继承的sleep方法。

  • 相关阅读:
    Pyhton学习——Day60
    Pyhton学习——Day58
    Python——微信数据分析
    C/C++文件指针偏移
    I/O流+统计文件词频
    vector概念
    new/delete工作机制
    Singleton单例类模式
    对象数组
    特殊成员函数
  • 原文地址:https://www.cnblogs.com/jeromesunny/p/3220543.html
Copyright © 2011-2022 走看看