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 << "\n多态,申明父类 调用子类:" << endl;
    Fish *fish = &bf;
    // #No3.若父类的方法不申明为virtual, 则调用不到子类方法
    fish->eat();

    cout << "\n多重继承end." << endl;

    return 0;
}

输出:

总结:

#No1. 多继承时,子类都继承animal基类,此时animal构造器会调用多次, java C#等单继承也是设计者充分考虑这个问题
#No2.若没有下面eat方法,两个子类都有eat方法,当调用BirdFish.eat时会报: eat is  ambiguous: 模棱两可的 candidates: 候选人 here, 编译不通过,提示二义性
     若只有一个子类有eat方法则不会报错
#No3.若父类的方法不申明为virtual, 则调用不到子类方法

猜你喜欢

转载自www.cnblogs.com/do-your-best/p/11205004.html