2622: B 虛拟繼承(虛基類)-沙發床(改錯題)
時間限制: 1 Sec
記憶體限制: 128 MB
送出: 487
解決: 393
題目描述
有一種特殊的床,既能當床(Bed)用又能當沙發(Sofa)用,是以叫沙發床(SleeperSofa)。
同時床和沙發又是一種特殊的家具(Furniture),具有一切家具的特性。
利用虛拟繼承(虛基類)建立一個類的多重繼承,沙發床繼承了床和沙發的特性。
下面的程式中,在begin到end部分存在文法錯誤。請改正錯誤,使程式按下面輸入輸出的規定運作。
注意:隻送出修改過的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; //床的寬
}; //沙發類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();
}
};//********************* end ********************
int main()
{
double weight,length,width,height;
cin>>weight>>length>>width>>height; SleeperSofa ss(weight,length,width,height);
ss.display();
return 0;
}
輸入
依次輸入沙發床的重量、長、寬、高
輸出
依次輸出沙發床的重量、長、寬、高
樣例輸入
200 1.8 1.5 1.2
樣例輸出
weight:200
length:1.8
width:1.5
height:1.2
提示
改錯思路有多種,隻要程式能運作出正确結果,怎樣改錯都可以
迷失在幽谷中的鳥兒,獨自飛翔在這偌大的天地間,卻不知自己該飛往何方……
#include <iostream>
using namespace std;
//家具類Furniture
class Furniture
{
public:
Furniture(double w)
{
weight=w;
}
void display()
{
cout<<"weight:"<<weight<<endl;
}
protected:
double weight; //家具重量
};
//床類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 Furniture
{
public:
SleeperSofa(double we,double l,double wi,double h):Bed(we,l,wi),Sofa(we,h),Furniture(we) { }
void display()
{
cout<<"weight:"<<weight<<endl;
Bed::display();
Sofa::display();
}
protected:
double weight=200;
};
int main()
{
double weight,length,width,height;
cin>>weight>>length>>width>>height;
SleeperSofa ss(weight,length,width,height);
ss.display();
return 0;
}