天天看点

c++多重继承和虚继承

多重继承

多重继承是指从多个直接基类中产生派生类的能力。

多重继承的派生类继承了所有父类的属性。

struct Base1 {

Base1() = default;

Base1(const string&);

Base1(shared_ptr<int>);

};

struct Base2 {

Base2() = default;

Base2(const string&);

Base2(int);

};

struct D1 :public Base1, public Base2 {

using Base1::Base1;

using Base2::Base2;

D1(const string& s) :Base1(s), Base2(s) {}

D1() = default;

};

虚继承

虚继承的目的是令某个类做出声明,承诺愿意共享它的基类。其中,共享的基类对象称为虚基类。

虚继承就是为了解决继承中的二义性。

class ZooAnimal {};

class Raccoon : public virtual ZooAnimal {};//ZooAnimal定义成了Raccoon和Bear的虚基类。

class Bear : virtual public ZooAnimal {};//两种方式相同

因为Bear和Raccoon是虚继承,所以Panda中只有一个ZooAnimal基类部分

class Panda : public Raccoon, public Bear {};

继续阅读