建立一个类Wheel,包含私有数据成员diameter和width,建立一个类body,包含私有数据length、width、height、和color以及公有函数getcolor、getdimension,建立一个类Car,包含私有数据name、manufacturer、year、Wheel类的对象body、Wheel类的对象wheel以及公有函数information,用来显示汽车各种信息
时间: 2023-07-10 21:13:57 浏览: 114
js类中的公有变量和私有变量
好的,我会根据您的要求来编写代码。代码如下:
```
#include <iostream>
#include <string>
using namespace std;
class Wheel {
private:
float diameter;
float width;
public:
Wheel(float dia, float wid) : diameter(dia), width(wid) {}
float getDiameter() const {
return diameter;
}
float getWidth() const {
return width;
}
};
class Body {
private:
float length;
float width;
float height;
string color;
public:
Body(float len, float wid, float hei, const string& col) :
length(len), width(wid), height(hei), color(col) {}
string getColor() const {
return color;
}
string getDimension() const {
return to_string(length) + " x " + to_string(width) + " x " + to_string(height);
}
};
class Car {
private:
string name;
string manufacturer;
int year;
Wheel wheel;
Body body;
public:
Car(const string& n, const string& m, int y, const Wheel& w, const Body& b) :
name(n), manufacturer(m), year(y), wheel(w), body(b) {}
void information() const {
cout << "Name: " << name << endl;
cout << "Manufacturer: " << manufacturer << endl;
cout << "Year: " << year << endl;
cout << "Wheel diameter: " << wheel.getDiameter() << endl;
cout << "Wheel width: " << wheel.getWidth() << endl;
cout << "Body color: " << body.getColor() << endl;
cout << "Body dimension: " << body.getDimension() << endl;
}
};
int main() {
Wheel wheel(17, 8);
Body body(4500, 1800, 1400, "red");
Car car("Model X", "Tesla", 2021, wheel, body);
car.information();
return 0;
}
```
在这个代码中,我们为Body类和Car类添加了两个公有函数getcolor和getdimension,分别用于获取车身颜色和尺寸。同时,我们还添加了一个公有函数information,用于显示汽车的各种信息。在此之前,我们先在main函数中初始化了一个Car对象,然后调用了它的information函数来显示汽车的信息。
如果您有任何问题或者需要进一步帮助,请随时告诉我。
阅读全文