设计一个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;
}