C++上机实验五 继承与派生

实验五 继承和派生

实验内容1:

编写一个程序设计一个汽车类vehicle,包含的数据成员有车轮个数wheels和车重weight。小车类car是它的公有派生类其中包含载人数passenger_load。卡车类truck是vehicle的公有派生类其中包含载人数passenger_load和载重量payload,每个类都有相关数据的输出函数,用以测试构造函数调用顺序,以及成员变量初始化及数据输出等。 程序清单:

#include

class vehicle //定义汽车类 {

private: int wh; //车轮数 float we; //重量 public: vehicle(int wheels,float weight){wh=wheels;we=weight;} int get_wheels(){return wh;} float get_weight(){return we;} void show(){cout<<\汽车:\ void print() { cout<<\车轮数为:\个\ cout<<\车重为:\吨\ } };

class car:public vehicle //公有派生小车类 { int wh,pa; float we; public: car(int wheels,float weight,int passengers):vehicle(wheels,weight) { pa=passengers; } int get_passengers(){return pa;} void print() { cout<<\小车:\ vehicle::print(); cout<<\载人数为:\个\ }

};

class truck:public vehicle //公有派生卡车类 { int wh,pa; float we,pay; public: truck(int wheels,float weight,int pay_load):vehicle(wheels,weight) { pa=passenger_load; pay=pay_load; } int get_passenger_load() {

return pa; } float get_pay_load() { return pay; } void print() { cout<<\卡车:\ vehicle::print(); cout<<\载人数为:\个\ cout<<\载重为:\吨\ } };

void main() { vehicle ve1(8,5); ve1.show(); ve1.print(); car car1(4,1,5); car1.print(); truck tr1(6,8,2,10); tr1.print(); }

passenger_load,float

运行结果:

上图是第一次的试验运行结果,由此可以分析各构造函数的调用顺序,但是也可以看到:

“汽车车轮数”、“汽车车重”调用了三次,且后面两次出现了错误;“小车车轮数”、“小车车重”、“卡车车轮数”、“卡车车重”均出现了错误。将程序修改后得到的最终运行结果如下:

实验内容2:

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4