题目:
- 定义一个或多个类,来描述以下需求:
汽车,有多个轮胎,一个发动机,品牌,型号, 价格,
行驶里程。
轮胎,有品牌,尺寸,气压。
发动机,有品牌,型号。
分析:通过分析,可以得出我们应该创建三个类
分别为汽车,轮胎,发动机
发动机类的代码:(Engine.h)
#pragma once
//发动机,有品牌,型号
#include<string>
using namespace std;
class Engine
{
public:
string getband();
string gettype();
Engine(string band,string type);
Engine();
private:
string band;
string type;
};
cpp代码:
#include "Engine.h"
string Engine::getband() {
return band;
}
string Engine::gettype() {
return type;
}
Engine::Engine(string band, string type)
{
this->band = band;
this->type = type;
}
Engine::Engine()
{
band = "宝马引擎";
type = "X5";
}
轮胎(Tiry.h):
#pragma once//有品牌,尺寸,气压
#include<string>
using namespace std;
class Tiry
{
public:
Tiry(string band);
string getband();
int getsize();
int getpressure();
private:
string band;
int size;
int pressure;
};
轮胎(tiry.cpp):
#include "Tiry.h"
Tiry::Tiry(string band)
{
this->band = band;
this->size = 3;
this->pressure = 6;
}
string Tiry::getband()
{
return band;
}
int Tiry::getsize()
{
band = "米其林";
size = 20;
pressure = 20;
return size;
}
int Tiry::getpressure()
{
return pressure;
}
car.h:在car类中除了平常定义的型号,还需要将轮胎和发动机这两个对象在car中进行组合,因为汽车有四个发动机所以需要定义一个对象数组
#pragma once
#include<string>
#include<vector>
#include"Engine.h"
#include"Tiry.h"
using namespace std;
class Tiry;
class Engine;
class Car
{
public:
Car(string carband, string carmodel
, int price, int distance, string en_brand,
string en_type,string ti_band);
string getband();
string getmodel();
int getprice();
int getdistance();
string getcar();
private:
Engine engine;
Tiry tiry[4];
string band; //品牌
string model;//类型
int price;
int distance;
};
car.cpp:
#include "Car.h"
#include<iostream>
#include<sstream>
using namespace std;
Car::Car(string carband, string carmodel,
int price, int distance,
string en_brand, string en_type,
string ti_band) :engine(en_brand, en_type),
tiry{ ti_band ,ti_band ,ti_band,ti_band }
{
this->band = carband;
this->model = carmodel;
this->price = price;
this->distance = distance;
}
string Car::getband()
{
return band;
}
string Car::getcar()
{
stringstream ret;
ret << "汽车品牌:" << band << "-汽车类型:" << model
<< "-汽车价格:" << price << "-汽车行驶距离:" <<
distance << endl << "-发动机品牌:" << engine.getband()
<< "-发动机类型:" << engine.gettype() << endl
<< "-轮胎类型:" << tiry[0].getband() << endl;
return ret.str();
}
string Car::getmodel()
{
return model;
}
int Car::getprice()
{
return price;
}
int Car::getdistance()
{
return distance;
}
主函数:
#include<iostream>
#include<Windows.h>
#include"Engine.h"
#include"Car.h"
#include"Tiry.h"
using namespace std;
int main() {
Car car("兰博基尼","911",
2000000,0,"奥迪","a6","米其林");
cout << car.getcar();
system("pause");
return 0;
}