OJ嘻唰唰之改错题(6)-虚拟继承(虚基类)沙发床

问题及代码:
/*
*Copyright(c)2014,烟台大学计算学院
*All  rights reserved.
*文件名称:test.cpp
*作者:陈银丽
*完成日期:2015年7月7日
*版本号:v1.0
*
*问题描述:虚拟继承(虚基类)—沙发床.有一种特殊的床,既能当床(Bed)用又能当沙发(Sofa)用,所以叫沙发床(SleeperSofa)。同时床和沙发
又是一种特殊的家具(Furniture),具有一切家具的特性。利用虚拟继承(虚基类)建立一个类的多重继承,沙发床继承了床和沙发的特性。下面
的程序中,在begin到end部分存在语法错误。请改正错误,使程序按下面输入输出的规定运行。注意:只提交修改过的begin到end部分的代码。
*输入描述:存在错误的代码
//床类Bed
class Bed: public Furniture
{
public:
Bed(double we,double l,double wi):Furniture(we),length(l),width(wi){}
void display()
{
cout<<"length:"<<length<<endl;
cout<<"width:"<<width<<endl;
}
protected:
double length; //床的长
double width; //床的宽
};

//沙发类Sofa
class Sofa: public Furniture
{ public:
Sofa(double w,double h):Furniture(w),height(h){}
void display()
{
cout<<"height:"<<height<<endl;
}
protected:
double height; //沙发的高度
};

//沙发床
class SleeperSofa:public Bed, public Sofa
{public:
SleeperSofa(double we,double l,double wi,double h):Bed(we,l,wi),Sofa(we,h){ }
void display()
{
cout<<"weight:"<<weight<<endl;
Bed::display();
Sofa::display();
}
};
*程序输出:
*/

#include <iostream>
using namespace std;

//家具类Furniture
class Furniture
{
public:
Furniture(double w)
{ weight=w; }
void display()
{
cout<<"weight:"<<weight<<endl;
}
protected:
double weight; //家具重量
};

class Bed: public Furniture
{
public:
Bed(double we,double l,double wi):Furniture(we),length(l),width(wi){}
void display()
{
Furniture::display();
cout<<"length:"<<length<<endl;
cout<<"width:"<<width<<endl;
}
protected:
double length; //床的长
double width; //床的宽
};

//沙发类Sofa
class Sofa: public Furniture
{ public:
Sofa(double w,double h):Furniture(w),height(h){}
void display()
{
cout<<"height:"<<height<<endl;
}
protected:
double height; //沙发的高度
};

//沙发床
class SleeperSofa:public Bed, public Sofa
{public:
SleeperSofa(double we,double l,double wi,double h):Bed(we,l,wi),Sofa(we,h){ }
void display()
{
Bed::display();
Sofa::display();
}
};
int main()
{
double weight,length,width,height;
cin>>weight>>length>>width>>height;

SleeperSofa ss(weight,length,width,height);
ss.display();

return 0;
}

知识点总结:虚基类,使得在继承间接共同基类时只保留一份成员。

学习心得:改错有很多方式,不必拘泥于一种

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值