[YTU]_2622(B 虚拟继承(虚基类)-沙发床(改错题))
題目描述
?有一種特殊的床,既能當(dāng)床(Bed)用又能當(dāng)沙發(fā)(Sofa)用,所以叫沙發(fā)床(SleeperSofa)。
同時(shí)床和沙發(fā)又是一種特殊的家具(Furniture),具有一切家具的特性。
利用虛擬繼承(虛基類)建立一個(gè)類的多重繼承,沙發(fā)床繼承了床和沙發(fā)的特性。
下面的程序中,在begin到end部分存在語法錯(cuò)誤。請改正錯(cuò)誤,使程序按下面輸入輸出的規(guī)定運(yùn)行。
注意:只提交修改過的begin到end部分的代碼。
#include <iostream>
using namespace std;
//家具類Furniture
class Furniture
{
public:
Furniture(double w)
{ weight=w; }
void display()
{
cout<<"weight:"<<weight<<endl;
}
protected:
double weight; //家具重量
};
//******************** begin ********************
//床類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; //床的寬
};
//沙發(fā)類Sofa
class Sofa: public Furniture
{ public:
Sofa(double w,double h):Furniture(w),height(h){}
void display()
{
cout<<"height:"<<height<<endl;
}
protected:
double height; //沙發(fā)的高度
};
//沙發(fā)床
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();
}
};
//********************* end ********************
int main()
{
double weight,length,width,height;
cin>>weight>>length>>width>>height;
SleeperSofa ss(weight,length,width,height);
ss.display();
return 0;
}
輸入
依次輸入沙發(fā)床的重量、長、寬、高 ?
輸出
依次輸出沙發(fā)床的重量、長、寬、高
樣例輸入
200 1.8 1.5 1.2樣例輸出
weight:200 length:1.8 width:1.5 height:1。。。。 #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:virtual 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; }; class Sofa:virtual public Furniture { public:Sofa(double w,double h):Furniture(w),height(h){}void display(){cout<<"height:"<<height<<endl;} private:double height; }; class SleeperSofa:public Bed,public Sofa { public:SleeperSofa(double we,double l,double wi,double h):Furniture(we),Bed(we,l,wi),Sofa(we,h){}void display(){cout<<"weight:"<<weight<<endl;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; }總結(jié)
以上是生活随笔為你收集整理的[YTU]_2622(B 虚拟继承(虚基类)-沙发床(改错题))的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [YTU]_2566( 虚基类练习:动物
- 下一篇: [YTU]_2476(E3 继承了,成员