第5章习题参考答案 下载本文

内容发布更新时间 : 2024/6/1 15:09:43星期一 下面是文章的全部内容请认真阅读。

9. 假定车可分为货车和客车,客车又可分为轿车、面包车和公共汽车。请设计相应的类层次结构。

说明:可以把轿车、面包车和公共汽车定义为客车类的对象 参考程序:

#include using namespace std;

class vehicle {

public:

// 定义基类vehicle // 公有函数成员

vehicle(int in_wheels,float in_weight); // 给数据成员初始化 int get_wheels(); // 获取车轮数 float get_weight(); // 获取汽车重量 void setWeels(int wls);

void setWeight(float wt); void display(){ cout<<\车轮数:\

<<\ 汽车重量:\ }

private: // 私有数据成员 int wheels; // 车轮数

float weight; // 表示汽车承重 };

vehicle::vehicle(int in_wheels,float in_weight){ }

float vehicle::get_weight(){ }

int vehicle::get_wheels(){ return wheels; }

void vehicle::setWeels(int wls){ }

wheels = wls; return weight; wheels = in_wheels; weight = in_weight;

void vehicle::setWeight(float wt){

weight = wt;

}

class truck:public vehicle // 定义货车类truck {

private: // 新增私有数据成员 float weight_load; // 承重

public: // 新增公有成员函数 truck(int wheel,float wt,float wl):vehicle(wheel,wt){ weight_load = wl; }

float getLoads(){ return weight_load; }

void display(){ } };

//车和客车,客车又可分为轿车、面包车和公共汽车 class car:public vehicle // 定义客车类car {

int passenger_load; public:

void setPassengers(int people){

// 新增私有数据成员,表示载客数

// 新增公有成员函数

vehicle::display();

cout<<\汽车承重\

car(int in_wheels,float in_weight,int people=4):vehicle(in_wheels,in_weight) {

passenger_load = people; }

int getPassengers(){ return passenger_load; }

};

passenger_load = people; }

void display(){

vehicle::display();

cout<<\载客数:\}

void main(){ truck truck1(8,400,100000);

car car1(4,20);

car saloon_car(4,10,5); car microbus(6,10,18); car bus(6,20,30); // 显示相关信息 truck1.display();

cout<<\car1.display();

cout<<\saloon_car.display();

cout<<\microbus.display();

cout<<\bus.display();

// 货车 // 客车 // 轿车 // 面包车 // 公共汽车

}

程序的运行结果: 车轮数:8 汽车重量:400 汽车承重100000 ---------------------

车轮数:4 汽车重量:20 载客数:4

---------------------

车轮数:4 汽车重量:10 载客数:5

---------------------

车轮数:6 汽车重量:10