12月测试题:7.能坐几个人

设家具类属性有:家具类型、家具材料、家具价格;
沙发类有沙发类型、沙发材料、沙发价格以及座位数(默认为3)
编程建立上述两个类,并在main函数中,创建2个沙发对象,计算输出沙发共能坐几个人。

给定后置代码:

int main(){
	double a,b;
	int c;
	cin>>a>>b>>c;
	Sofa s1("布艺",a),s2("木材",b,c);
	Furniture f=s1;
	cout<<f.getType()<<":主材料="<<f.getMaterial()<<",价格="<<f.getPrice()<<endl;
	cout<<s2.getType()<<":主材料="<<s2.getMaterial()<<",价格="<<s2.getPrice()<<endl;
	cout<<"能坐"<<s1+s2<<"人"<<endl;
	return 0;
}

思路:父类Furniture,子类Sofa
父类包含家具类型、材料、价格、两个string型一个double型
子类升级出int型座位
难点运算符重写;

#include<iostream>
#include<cstring>
using namespace std;
class Furniture 
{
	public :
		string Type;//家具类型 
		string Material;//家具材料 
		double Price;//家具价格 
		Furniture(const string &a,const string &b,double c)
		{//构造Furniture 
			Type=a;
			Material=b;
			Price=c;
		}
		string getType()
		{//调用类型 
			return  Type;
		}
		string getMaterial() 
		{//调用材料 
			return Material;
		}
		double getPrice()
		{//调用价格 
			return Price;
		};
};

class Sofa:public Furniture
{//沙发公有继承furniture 
	public:
		int num;//添加int型坐位 
	 	Sofa(const string &a,double b):Furniture("沙发",a,b)
	 	{//构造Sofa缺少num的 设置默认num=3 
	 		num=3;
		}
		Sofa(const string &a,double b,int c):Furniture("沙发",a,b)
	 	{//构造Sofa带num的 
	 		num=c;
		};
		int operator +(Sofa &s1,Sofa &s2) 
		{//重载计算符+ 以后再遇见这种的 首先要判断调用结束是要返回什么样的值
		//本题是返回int 那么就是int型 operator重写+ 参与计算的两个sofa为参数要用&
		 
			return s1.num+s2.num;
		}	
};

int main()
{
	double a,b;
	int c;
	cin>>a>>b>>c;
	Sofa s1("布艺",a),s2("木材",b,c);
	Furniture f=s1;//定义父类f=子类s1 
	cout<<f.getType()<<":主材料="<<f.getMaterial()<<",价格="<<f.getPrice()<<endl;
	cout<<s2.getType()<<":主材料="<<s2.getMaterial()<<",价格="<<s2.getPrice()<<endl;
	cout<<"能坐"<<s1+s2<<"人"<<endl;//涉及计算符+重写 返回类型为int 
	return 0;
}
发布了28 篇原创文章 · 获赞 12 · 访问量 3813

猜你喜欢

转载自blog.csdn.net/q767410241/article/details/84844426