定义一个名为Vehicles(交通工具)的基类,该类中应包含String类型的成员属性brand(商标)和color(颜色),还应包含成员方法run(行驶,在控制台显示“我已经开动了”)和showInfo(显示信息,在控制台显示商标和颜色),并编写构造方法初始化其成员属性。
编写Car(小汽车)类继承于Vehicles类,增加int型成员属性seats(座位),还应增加成员方法showCar(在控制台显示小汽车的信息),并编写构造方法。 编写Truck(卡车)类继承于Vehicles类,增加float型成员属性load(载重),还应增加成员方法showTruck(在控制台显示卡车的信息),并编写构造方法。 在main方法
#include<iostream>
#include<iomanip>
using namespace std;
class Vehicles
{
public:
string brand,color;
void run();
Vehicles(string b,string c);
void showInfo();
};
Vehicles::Vehicles(string b,string c)
{
brand=b;
color=c;
}
void Vehicles::run()
{
cout<<"我已经开动了"<<endl;
}
void Vehicles::showInfo()
{
cout<<"商标:"<<brand<<endl;
cout<<"颜色:"<<color<<endl;
}
class Car:public Vehicles
{
public:
int seats;
void showCar();
Car(string b,string c,int s);
};
void Car::showCar()
{
cout<<"小汽车-------------------"<<endl;
cout<<"商标:"<<brand<<endl;
cout<<"颜色:"<<color<<endl;
cout<<"座位:"<<seats<<endl;
}
Car::Car(string b,string c,int s):Vehicles(b,c)
{
seats=s;
brand=b;
color=c;
}
class Truck:public Vehicles
{
public:
float load;
void showTruck();
Truck(string b,string c,float l);
};
Truck::Truck(string b,string c,float l):Vehicles(b,c)
{
load=l;
brand=b;
color=c;
}
void Truck::showTruck()
{
cout<<"大卡车-------------------"<<endl;
cout<<"商标:"<<brand<<endl;
cout<<"颜色:"<<color<<endl;
cout<<"载重:"<<load<<endl;
}
int main()
{
Vehicles v1("清风","绿色");
v1.run();
v1.showInfo();
Car c1("心相印","蓝色",5);
c1.showCar();
Truck t1("洁柔","粉色",100.9);
t1.showTruck();
return 0;
}
中测试以上各类
结果如下