#include<iostream>
using namespace std;
class Furniture{
public:
Furniture(int weight):weight_(weight)
{
cout<<"Furniture............"<<endl;
}
~Furniture()
{
cout<<"~Furniture()............"<<endl;
}
int weight_;
};
class Bed: virtual public Furniture{
public:
Bed(int weight):Furniture(weight)
{
cout<<"Bed.........."<<endl;
}
~Bed()
{
cout<<"~Bed().........."<<endl;
}
void sleep()
{
cout<<"sleep..."<<endl;
}
};
class Soft:virtual public Furniture
{
public:
Soft(int weight):Furniture(weight)
{
cout<<"Soft.........."<<endl;
}
~Soft()
{
cout<<"~Soft()........."<<endl;
}
void WatchTV()
{
cout<<"watch Tv...."<<endl;
}
};
class SoftBed:public Bed,public Soft{
public:
SoftBed(int weight):Bed(weight),Soft(weight),Furniture(weight)
{
FoldIn();
}
~SoftBed()
{
cout<<"~SoftBed()........."<<endl;
}
void FoldIn()
{
cout<<"FoldIn............"<<endl;
}
void FoldOut()
{
cout<<"FoldOut..........."<<endl;
}
};
int main(){
//Bed bed(10);
//bed.sleep();
SoftBed softBed(5);
//bedSoft.weight_=10;error,error C2385: 对“weight_”的访问不明确
//可能是“weight_”(位于基“Bed”中)
// 也可能是“weight_”(位于基“Soft”中)
//softBed.Bed::weight_=10;
//softBed.Soft::weight_=20;
softBed.weight_=20;//error,存在二义性访问不明确
softBed.sleep();
softBed.WatchTV();
return 0;
}
//多重继承的优点
//1、派生类同时继承多个基类的成员,更好的利用其更好的软件重用
//2、可能存在大量的二义性,多个基类中可能包含同名的变量或函数
//多重继承中解决访问歧义的方法
// 基类名::数据成员(数据函数(参数列表))
//1、明确指定是访问那个基类的成员
// 当派生类从多个基类派生,而这些基类又从同一个基类派生,则在访问此基类中的成员时,将产生二义性
//解决方式:采用虚基类来解决
//声明方式:以virtual 修饰说明基类
//例如:class B1:virtual public BB
// 作用:1、主要解决多继承时可能发生的对同一基类继承多次而产生的二义性问题
// 2、为最远的派生类提供唯一的基类成员,而不重复产生多次拷贝
//3、在建立对象时,只有最远派生类的构造函数调用虚基类的构造函数时,该派生类的其他基类对虚基类构造函数的调用被忽略