类的声明和定义

设计一个Car类,它的数据成员要能够描述一部汽车的品牌,型号,颜色,生产地址,出厂日期和价格。类的成员函数包含构造函数和析构函数,同时还需要包括其它的成员函数,以提供合适的途径来访问数据成员(如汽车的款式或者价格等)。此外,类还需要提供一个compare成员函数,用来对两车进行比较(例如:比较价格和出场日期):

void compare(const Car&);

compare函数能够输出简短的结果比较报告。

 

代码如下:

#include <iostream>
#include <string>
#include <iomanip>
using  namespace std;
class Car{
public:
	Car(){cout<<"Constructor without parameters."<<endl;}
	Car(string b,string m,string c,string l,string d,float p);
	Car(const Car&);
	~Car(){cout<<"Deconstructor is called."<<endl;}

	void SetBrand(string brand){sBand=brand;}
	void SetModel(string model){sModel=model;}
	void SetColor(string color){sColor=color;}
	void SetLocation(string location){sLocation=location;}
	void SetDate(string date){sDate=date;}
	void SetPrice(float f){fPrice=f;}

	string GetBrand(){return sBand;}
	string GetModel(){return sModel;}
	string GetColor(){return sColor;}
	string GetLocation(){return sLocation;}
	string GetDate(){return sDate;}
	float GetPrice(){return fPrice;}

	void printInfo();
	void Compare(const Car&);
private:
	string sBand;
	string sModel;
	string sColor;
	string sLocation;
	string sDate;
	float fPrice;
};
Car::Car(string b,string m,string c,string l,string d,float p)
{
	sBand=b;
	sModel=m;
	sColor=c;
	sLocation=l;
	sDate=d;
	fPrice=p;
	cout<<"Constructor with parameters."<<endl;
}
Car::Car(const Car& car)
{
	sBand=car.sBand;
	sModel=car.sModel;
	sColor=car.sColor;
	sLocation=car.sLocation;
	sDate=car.sDate;
	fPrice=car.fPrice;
	cout<<"Copy constructor."<<endl;
}
void Car::printInfo()
{
	cout<<sBand <<" "<<sModel<<"颜色:"<<sColor<<";生产地址:"<<sLocation<<";日期:"<<sDate<<";价格"<<fPrice<<endl;
}
void Car::Compare(const Car& car)
{
	if(car.fPrice<fPrice)
		cout<<sBand <<" "<<sModel<<"价格比"<<car.sBand <<" "<<car.sModel<<"贵"<<endl;
	else
		cout<<sBand <<" "<<sModel<<"价格比"<<car.sBand <<" "<<car.sModel<<"便宜"<<endl;
}
int main()
{
	Car car1("audi","a4l","white","一汽","20190101",34);
	Car car2;
	car2=car1;
	car2.SetModel("q5");
	car2.SetPrice(45);
	car1.printInfo();
	car2.printInfo();
	car1.Compare(car2);

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值