定义一个名为Vehicles(交通工具)的基类,该类中应包含string类型的数据成员brand(商标)和color(颜色),还应包含成员函数run(行驶,在控制台显示“我已经开动了”)和showInfo(显示信息,在控制台显示商标和颜色),并编写构造函数初始化其数据成员的值。从Vehicles类派生出Car类(小汽车),增加int型数据成员seats(座位),还应增加成员函数showCar(在控制台显示小汽车的信息),并编写构造函数。在main函数中测试以上各类。
时间: 2023-12-30 09:07:05 浏览: 63
好的,以下是您提出的问题的代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
class Vehicles {
public:
Vehicles(string brand, string color) : brand(brand), color(color) {}
void run() {
cout << "我已经开动了" << endl;
}
void showInfo() {
cout << "商标:" << brand << endl;
cout << "颜色:" << color << endl;
}
protected:
string brand;
string color;
};
class Car : public Vehicles {
public:
Car(string brand, string color, int seats) : Vehicles(brand, color), seats(seats) {}
void showCar() {
cout << "商标:" << brand << endl;
cout << "颜色:" << color << endl;
cout << "座位数:" << seats << endl;
}
private:
int seats;
};
int main() {
Vehicles vehicle("奥迪", "黑色");
vehicle.showInfo();
vehicle.run();
Car car("宝马", "白色", 4);
car.showCar();
car.run();
return 0;
}
```
在上面的代码中,我们定义了一个名为 `Vehicles` 的基类,并在其中声明了 `brand` 和 `color` 两个成员变量,以及 `run()` 和 `showInfo()` 两个成员函数。
然后,我们从 `Vehicles` 类中派生出了 `Car` 类,并增加了 `seats` 成员变量和 `showCar()` 成员函数。
最后,在 `main` 函数中,我们分别创建了 `Vehicles` 和 `Car` 类的实例,并调用了它们的成员函数。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)