诚心请教C++类与继承问题
父类:Furniture//家具类type:string//家具类型
mat:string//家具主材料
price:double//家具价格
+Furniture()
+Furniture(string,string,double)
+getMat():string
+getPrice():double
+getTyep():string
继承类1:Sofa//沙发类
seats:int //座位数
+Sofa()
+Sofa(string,double,int)
+getSeats():int
继承类2:Bed//床类
bedtype:string //床类型
+Bed()
+Bed(string,double,string)
+getBedType():string
Furniture、Bed和Sofa关系如上图,请先声明并定义这三个类完成以下程序:
void show(Furniture *f)
{
…//输出f所指向的家具类型、主材料和价格
}
int main()
{
Sofa sa(“竹子”,870,3);
Bed ba(“木材”,1200,”单人”);
Furniture * sb=new Sofa(“钢材”,410,1);
show(&sa);
show(&ba);
show(sb);
delete sb;
return 0;
}
输出结果:
家具类型:沙发 主材料:竹子 价格:870
家具类型:床 主材料:木材 价格:1200
家具类型:沙发 主材料:钢材 价格:410
我的程序如下:(诚心请教,帮忙看一下:谢谢!)
#include<iostream>
#include<string>
using namespace std;
class Furniture
{
protected:
string mat;//家具主材料
double price;//家具价格
string type;//家具类型
public:
Furniture(){}
Furniture(string m,double p,string t="0")
{
mat=m;
price=p;
type=t;
}
string getType()
{return type;}
string getMat()
{return mat;}
double getPrice()
{return price;}
};
class Sofa:public Furniture
{
private:
int seats;
public:
Sofa(){}
Sofa(string m,double p,int s):Furniture(m,p,type="沙发")//{type="沙发";}
{seats=s;}
int getSeats()
{return seats;}
};
class Bed:public Furniture
{
private:
string bedtype;
public:
Bed(){}
Bed(string m,double p,string b):Furniture(m,p,type="床")
{bedtype=b;}
string getBedType()
{return bedtype;}
void show(Furniture *f)
{
cout<<"家具类型:"<<f->getType()<<" "<<"主材料:"<<f->getMat()<<" "<<"价格:"<<f->getPrice()<<endl;
}
};
int main()
{
Sofa sa("竹子",870,3);
Bed ba("木材",1200,"单人");
Furniture * sb=new Sofa("钢材",410,1);
show(&sa);
show(&ba);
show(sb);
delete sb;
return 0;
}