解决派生类多重继承产生的二义性

#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、在建立对象时,只有最远派生类的构造函数调用虚基类的构造函数时,该派生类的其他基类对虚基类构造函数的调用被忽略

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值