zoukankan      html  css  js  c++  java
  • C++多重继承实践

    实践代码如下:

    #include <iostream>
    using namespace std;
    
    class Animal {
    
    private:
        int hash;
    
    public:
        Animal() {
            hash = 100;
            cout << "Animal构造器, hash:" << hash << endl;
        }
        virtual ~Animal() {
        }
        int getHash() {
            return hash;
        }
    };
    
    class Bird: virtual public Animal {
    public:
        Bird() {
            cout << "Bird构造器" << endl;
        }
        void fly() {
            cout << "鸟在天上飞~~~" << endl;
        }
        void eat() {
            cout << "鸟吃东西~~~" << endl;
        }
    };
    class Fish: public virtual Animal {
    public:
        Fish() {
            cout << "Fish构造器" << endl;
        }
        virtual ~Fish(){
    
        }
        void fly() {
            cout << "鱼在水里游~~~" << endl;
        }
        virtual void eat() {
            cout << "鱼吃东西~~~" << endl;
        }
    };
    
    // 构造器由继承顺序从左往右初始化
    // #No1. 多继承时,子类都继承animal基类,此时animal构造器会调用多次, java C#等单继承也是设计者充分考虑这个问题
    class BirdFish: public Bird, public Fish {
    
    public:
        BirdFish() {
            cout << "BirdFish构造器" << endl;
        }
        // #No2.若没有下面eat方法,两个子类都有eat方法,当调用BirdFish.eat时会报: eat is  ambiguous: 模棱两可的 candidates: 候选人 here, 编译不通过,提示二义性
        // 若只有一个子类有eat方法则不会报错
        void eat() {
            cout << "飞鸟吃东西~~~" << endl;
        }
        void action() {
            cout << "飞鸟既能飞又能游泳~~~" << endl;
        }
    };
    
    int main() {
    
        cout << "多重继承实践:" << endl;
    
        cout << "申明子类但调用父类:" << endl;
        BirdFish bf;
        bf.action();
        bf.eat();
        bf.Bird::eat();
        bf.Fish::eat();
    
        cout << "
    多态,申明父类 调用子类:" << endl;
        Fish *fish = &bf;
        // #No3.若父类的方法不申明为virtual, 则调用不到子类方法
        fish->eat();
    
        cout << "
    多重继承end." << endl;
    
        return 0;
    }

    输出:

    总结:

    #No1. 多继承时,子类都继承animal基类,此时animal构造器会调用多次, java C#等单继承也是设计者充分考虑这个问题
    #No2.若没有下面eat方法,两个子类都有eat方法,当调用BirdFish.eat时会报: eat is  ambiguous: 模棱两可的 candidates: 候选人 here, 编译不通过,提示二义性
         若只有一个子类有eat方法则不会报错
    #No3.若父类的方法不申明为virtual, 则调用不到子类方法
  • 相关阅读:
    学习ObjectC,GUNstep安装在windows上
    Why std::binary_search of std::list works, sorta ...(转载)
    android开发_Button控件
    Android开发模拟器的使用02
    Android开发环境搭建01
    android开发TextView控件学习
    Java 利用poi把数据库中数据导入Excel
    Cannot create PoolableConnectionFactory (Communications link failure)Connection refused: connect
    Android开发第一个程序Helloworld
    java的poi技术读取和导入Excel
  • 原文地址:https://www.cnblogs.com/do-your-best/p/11205004.html
Copyright © 2011-2022 走看看