在c++中,虚拟继承(virtual inheritance)和虚基类(virtual base class)是多重继承(multiple inheritance)中的内容,用来解决diamond problem。
先来看一个例子
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){cout<<"delicious!"<<endl;}
};
// Two classes virtually inheriting Animal:
class Mammal : virtual public Animal {
public:
void breathe(){}
};
class WingedAnimal : virtual public Animal {
public:
void flap(){}
};
// A bat is still a winged mammal
class Bat : public Mammal, public WingedAnimal {
};
int main(){
Bat b;
b.eat();
return 0;
}
网友评论