题目:定义一个或多个类,来描述以下需求:
汽车,有多个轮胎,一个发动机,品牌,型号,价格,行驶里程。
轮胎,有品牌,尺寸,气压。
发动机,有品牌,型号。
Car.h
#pragma once #include "Tire.h" #include "Engine.h" #include <sstream> #include <iostream> class Car { public: Car(const string &carBrand,const string &carVer,int carPrice,const string &engineBrand,float engineVer,const string &tireBrand="米其林"); ~Car(); Engine getEngin() const; const Tire* getTire(int i)const; string getBrand() const; string getVersion() const; int getPrice() const; int getMiles() const; string description() const; private: Engine engine; Tire tires[4]; string brand;//版本 string version;//型号 int price; int miles;//行驶里程数 };
Car.cpp
#include "Car.h" Car::~Car() { cout << "_FUNCITON_" << endl; } Car::Car(const string& carBrand, const string& carVer, int carPrice, const string& engineBrand,float engineVer, const string& tireBrand) :engine(engineBrand,engineVer), tires{tireBrand,tireBrand,tireBrand,tireBrand} { this->brand = carBrand; this->price = carPrice; this->version = carVer; this->miles = 0; } Engine Car::getEngin() const { return engine; } const Tire* Car::getTire(int i) const { if (i >= 1 && i <= 4) { return &tires[i]; } return NULL; } string Car::getBrand() const { return brand; } string Car::getVersion() const { return version; } int Car::getPrice() const { return price; } int Car::getMiles() const { return miles; } string Car::description() const { stringstream ret; ret << "汽车品牌:" << brand << "-" << version << "-$" << price << "/t/t引擎:" << engine.description() << "\t\t轮胎:" << tires[0].description(); return ret.str(); }
Engine.h
#pragma once #include <string> #include <iostream> using namespace std; class Engine { public: Engine(const string& brand, float version); ~Engine(); string description() const; private: string brand;//发动机品牌 float version;//发动机型号:x.x升 };
Engine.cpp
#include "Engine.h" #include <sstream> Engine::Engine(const string& brand, float version) { this->brand = brand; this->version = version; } Engine::~Engine() { cout << "_FUNCITON_" << endl; } string Engine::description() const { stringstream ret; ret << "品牌:" << brand << ",型号:" << version; return ret.str(); }
Tire.h
#pragma once #include <string> #include <iostream> using namespace std; class Tire { public: Tire(const string& brand="米其林"); ~Tire(); string getBrand() const; float getPressure() const; string description() const; private: string brand;//品牌 float pressure;//胎压 };
Tire.cpp
#include "Tire.h" #include <sstream> Tire::Tire(const string& brand) { this->brand = brand; this->pressure = 2.5; } Tire::~Tire() { cout << "_FUNCITON_" << endl; } string Tire::getBrand() const { return brand; } float Tire::getPressure() const { return pressure; } string Tire::description() const { stringstream ret; ret << "品牌:" << brand << "胎压:" << pressure; return ret.str(); }
main.cpp
#include <iostream> #include "Car.h" int main(void) { { Car car("宝马", "x7", 950000, "宝马", 3.5); cout << car.description() << endl; }; system("pause"); return 0; }