一.多继承
class Bed {
public:
void sleep() {
cout << "在床上睡觉" << endl;
}
};
class Sofa {
public:
void sit() {
cout << "在沙发上休息" << endl;
}
};
//沙发床
class SofaBed :public Bed,public Sofa//多继承
{
public:
void SleepAndSit() {
sleep();
sit();
}
};
int main() {
Bed b;
b.sleep();
Sofa s;
s.sit();
cout << "---------------" << endl;
SofaBed sb;
sb.SleepAndSit();
return 0;
}
结果:
弊端:
沙发床继承了床和沙发的材质m,导致不明确。
代码:
//家具
class Furniture {
public:
int m;//材质
};
//床
class Bed :public Furniture
{
public:
void sleep() {
cout << "在床上睡觉" << endl;
}
};
//沙发
class Sofa :public Furniture
{
public:
void sit() {
cout << "在沙发上休息" << endl;
}
};
//沙发床,多继承,此时类中有两个m
class SofaBed :public Bed,public Sofa//多继承
{
public:
void SleepAndSit() {
cout <<"Bed::m=" << Bed::m <<",Sofa::m:" << Sofa::m << endl;
}
};
int main() {
SofaBed sb;
sb.m=1;//错误:m不明确;
return 0;
}
解决方法:
方案一:加域名
问题:不明确现象依然存在。
int main() {
SofaBed sb;
sb.Bed::m = 1;
sb.Sofa::m = 2;
sb.SleepAndSit();
return 0;
}
结果:
方案二:虚继承
虚继承
添加virtual,实现虚继承,使孙子类继承爷爷辈的m,而不继承父亲辈的m。
作用:可以解决不明确现象。
原理:只申请一个m变量空间。
总结:出现这种菱形结构就加virtual!!!
代码:
//家具
class Furniture {
public:
int m;//材质
};
//床
class Bed :virtual public Furniture//改成虚继承
{
public:
void sleep() {
cout << "在床上睡觉" << endl;
}
};
//沙发
class Sofa :virtual public Furniture//改成虚继承
{
public:
void sit() {
cout << "在沙发上休息" << endl;
}
};
//沙发床,多继承,此时类中有两个m
class SofaBed :public Bed,public Sofa//多继承
{
public:
void SleepAndSit() {
cout <<"Bed::m=" << Bed::m <<",Sofa::m:" << Sofa::m << endl;
}
};
int main() {
SofaBed sb;
sb.m = 1;
sb.SleepAndSit();
return 0;
}
运行: