1 类的多继承
class Sofabed : public Sofa,public Bed
两个都是公有继承,如果不写默认为私有继承。
2 产生了二义性
如上,Sofa 和Bed,如果都有weight变量。
使用s.getWeight();/*error 二意性,引入虚拟继承*/
可以使用
s.Sofa::getWeight();
s.Bed::getWeight();
来区分,不过这样有点麻烦。
3 虚拟继承
1 先定义一个家具类
class Furniture {
private:
int weight;
public:
void setWeight(int weight) { this->weight = weight;}
int getWeight(void) {return this->weight;}
}
2 床和沙发都虚拟继承这个家具
class Sofa : virtual public Furniture{
private:
int a;
public:
void watchTV(void) { cout<<"watch TV"<<endl;}
};
class Bed : virtual public Furniture{
private:
int b;
public:
void sleep(void) {cout<<"sleep"<<endl;}
};
3 沙发床多继承这沙发和床
class Sofabed : public Sofa,public Bed {
private:
int c;
};
结论:虚继承时,共同的虚父类会存在于同个空间。