面向对象程序设计与C++语言 第二版 教学课件 作者 杨庚 王汝传 叶晓国 第九讲.ppt
文本预览下载声明
* * 第5章 派生与继承性 5.1 派生类 5.2 多重继承 5.3 类模板的派生 第九讲 派生与继承性 第5章 派生与继承性 5.1 派生类 5.2 多重继承 5.3 类模板的派生 派 生 类 (derived class) 为什么引入派生类 ? 自然地表示现实世界,是复杂的系统层次化,提高代码的重用性,增强语言功能,提高软件开发效益. 例如关于雇员和车辆的层次关系: Teacher(教师) Officer(行政) Worker(工人) Employee(雇员) Car(汽车) Sportscar(赛车) Vehicle(车辆) 第5章 派生与继承性 5.1 派生类 5.2 多重继承 5.3 类模板的派生 派生类定义方式 ? class base { public: …… protected: …… private: …… }; public class derivedName: protected base{..} private public、protected 和 private分别表示公有继承、保护继承和私有继承 第5章 派生与继承性 5.1 派生类 5.2 多重继承 5.3 类模板的派生 例1 基类车辆vehicle.h (因篇幅所限,我们 将类的实现放到头文件之中) #includeiostream.h class vehicle { public: private: }; vehicle(int aw, int ats, float ap) :weight(aw),topspeed(ats),price(ap) { } void print( ) { cout \n weight: weight pds; cout \n top speed: topspeed mph; cout \n price: $ price; int weight; //重量 int topspeed; //最高速度 float price; //价格 第5章 派生与继承性 5.1 派生类 5.2 多重继承 5.3 类模板的派生 //公有派生类汽车 car.h #include vehicle.h class car : public vehicle { public: private: }; car(int aw, int ats, float ap, int anc, int ahp) :vehicle(aw,ats,ap), numbercylinders(anc) , horsepower(ahp) { } void print( ) { vehicle::print( ); //调用基类的函数 cout \n cylinders: numbercylinders; cout \n horsepower: horsepower; int numbercylinders; //汽缸数 int horsepower; //马力 第5章 派生与继承性 5.1 派生类 5.2 多重继承 5.3 类模板的派生 //应用程序 main.cpp #include vehicle.h void main ( ) { vehicle av(15000, 60, 300000); //创建对象 car ac(3500, 100, 12000, 6, 120);//创建对象 av.print( ); //调用基类函数 ac.print( ); //调用派生类函数 } 结果: weight: 15000 pds top speed: 60 mph price $300000.00 weight: 3500 pds top speed: 100 mph price $12000.00 cylinders: 6 horsepower: 120 第5章 派生与继承性 5.1 派生类 5.
显示全部