定义一个名为Vehicles(交通工具)的基类,该类中应包含string类型的数据成员brand(商标)和color(颜色),还应包含成员函数run(行驶,在控制台显示“我已经开动了”)和showInfo(显示信息,在控制台显示商标和颜色),并编写构造函数初始化其数据成员的值。从Vehicles类派生出Car类(小汽车),增加int型数据成员seats(座位),还应增加成员函数showCar(在控制台显示小汽车的信息),并编写构造函数。在main函数中测试以上各类。
一、基类 Vehicles 剖析
首先定义基类 Vehicles
,它象征一般交通工具,涵盖 string
类型的数据成员 brand
(商标)与 color
(颜色),以此描述其基本特性。
基类构造函数 Vehicles(string brand, string color)
借助 this
指针为数据成员赋值,确保对象初始化时具备准确的商标与颜色信息。
成员函数 run
在控制台输出 “我已经开动了”,模拟交通工具启动;showInfo
则输出商标和颜色,呈现对象详情。
二、派生类 Car 解析
由 Vehicles
基类派生的 Car
类,除继承 brand
和 color
外,新增 int
型数据成员 seats
(座位),凸显小汽车专属属性。
Car
类构造函数 Car(string brand, string color, int seats)
借助初始化列表调用基类构造函数初始化继承成员,并为自身 seats
成员赋值。
showCar
函数先调用基类 showInfo
展示商标与颜色,再输出座位数量,全方位呈现小汽车信息。
三、实现代码
#include <iostream>using namespace std;#include <string>class Vehicles {public:Vehicles(string brand, string color) {this->brand = brand;this->color = color;}void run() { cout << "我已经开动了" << endl; }void showInfo() {cout << "商标: " << brand << endl;cout << "颜色: " << color << endl;}private:string brand;string color;};class Car :public Vehicles {public:Car(string brand, string color, int seats) :Vehicles(brand, color) {this->seats = seats;}void showCar() {showInfo();cout << "座位:" << seats << "个" << endl;}private:int seats;};int main(){Vehicles v("奥迪", "黑色");v.showInfo();cout << "==============" << endl;Car c("大众", "红色", 6);c.showCar();return 0;}