编程:VC++ 类的继承,构造函数,数据初始化
2012-10-29
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
/************************************************* 功能:类的继承,构造函数,数据初始化 作者:TAHO 时间:2012年10月29日 **************************************************/ #include <iostream.h> class vehicle { protected: int wheels,weight; public: vehicle(int i,int j) { wheels=i; weight=j; } int get2ws() //这里的return功能不能被写进构造函数vehicle(…)里,否则不被执行,构造函数只负责数据初始化,不负责返回数值等操作。 { return wheels; return weight; } }; class car:private vehicle //私有继承 { public: int passenger_load; car(int i,int j,int p_l):vehicle(i,j) //构造函数,有i,j,初始化了基类的成员i,j { passenger_load=p_l; cout<<“The wheels number of car is: ”<<wheels<<endl; cout<<“The weight of car is: ”<<weight<<endl; cout<<“The passenger load of car is ”<<passenger_load<<“nn”; } }; class truck:private vehicle //私有继承 { public: int passenger_load,payload; truck(int i,int j,int p_l,int pay_l):vehicle(i,j) //构造函数,有i,j,又一次初始化了基类的成员i,j,旧的i,j值被替换 { passenger_load=p_l; payload=pay_l; cout<<“The wheels number of truck is: ”<<wheels<<endl; cout<<“The weight of truck is: ”<<weight<<endl; cout<<“The passenger load of truck is ”<<passenger_load<<endl; cout<<“The payload of truck is ”<<payload<<“nn”; } }; void main() { car car1(4,10,6); truck truck1(6,25,2,40); } |