定义一个汽车类Car,其成员数据包括汽车编号id、品牌brand、发动机动力power和载客人数numOfPersons,
实现一个打印自身信息的成员函数printCar()。
定义默认构造函数、带所有成员数据的构造函数和拷贝构造函数。
设某单位有3个品牌都是“丰田”的汽车,且发动机动力和载客人数都一致,只是编号不同。
使用带所有成员数据的构造函数生成一个汽车对象,使用拷贝构造函数生成另外两个汽车对象,并通过调用修改编号的成员函数修改这个汽车对象的编号。
最后调用printCar()打印所有汽车对象的信息。
【要求】
给出Car类的析构函数。
---------------------------------------------------------------------------------------------------------------------------------
这个题太恶心了,填片段,不解释啦,全都是泪~~~~~
---------------------------------------------------------------------------------------------------------------------------------
#include? <iostream> #include? <cstring> using? namespace? std;
class Car { ????? public: ???????????? Car(); ???????????? Car(int pId,const? char*? pBrand,float? pPower,int pNumOfPersons); ???????????? Car(Car& c); ???????????? void printCar(); ???????????? ~Car(); ???????????? void? setId(int); ????? private: ????????????? int id; ????????????? char *brand; ????????????? int power; ????????????? int numOfPersons; ???????????? ? }; Car::Car() {????????? cout<<"Constructed? without? any? parameter."<<endl; } Car::Car(int? pId,? const? char*? pBrand,float? pPower,int? pNumOfPersons) { ?? ?id=pId; ??? brand=new char[strlen(pBrand)+1]; ??? if(brand!=0) ??????? { ?????? ??? ?strcpy(brand,pBrand); ?? ??? ?} ??? power=pPower; ??? numOfPersons = pNumOfPersons; ??? cout<<"Constructed? with? all? parameters."<<endl; } Car::Car(Car&? car) { ?? ?id = car.id+1; ??? brand=new char[strlen(car.brand)+1]; ???? if(brand!=0) ?? ?{ ?? ?strcpy(brand,car.brand); ?? ?} ??? power=car.power; ??? numOfPersons=car.numOfPersons; ??? cout<<"Deep? Constucted."<<endl; } Car::~Car() {???????? ? ??? delete[]? brand; ??? cout<<"Deconstructed."<<endl; } void? Car::printCar() {?????????? ? ?? ?cout<<"id:? "<<id<<",? " ??? <<"brand:? "<<brand<<",? " ??? <<"power:? "<<power<<",? " ??? <<"numOfPersons:? "<<numOfPersons<<endl; } void? Car::setId(int? pId) { ?? ?id = pId; } int? main() {???????? ? ?? ?Car? car1(1001,"Toyota",1.8f,5); ??? Car? car2(car1); ??? car2.setId(1002); ??? Car? car3=car1; ??? car3.setId(1003); ??? car1.printCar(); ??? car2.printCar(); ??? car3.printCar(); ??? return? 0; }
|