• 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;
    }
    
  • 相关阅读:
    css 背景透明 适合所有浏览器
    Razor中Html.DropDownListFor用法
    outlook2010如何初始化设置
    移除文件关联
    MVC中的Html.ActionLink的介绍(转)
    DES可逆加解密
    Razor视图下服务器代码给Javascript变量赋值
    js获取url参数值
    python 3 简单线程、数据库操、Mssql访问示例
    ps快捷键
  • 原文地址:https://www.cnblogs.com/hzshisan/p/12571099.html
Copyright © 2020-2023  润新知