C++实验五多态..docx

  1. 1、本文档共8页,可阅读全部内容。
  2. 2、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
C实验五多态.

福建工程学院实验报告面向对象程序设计(C++)专业电子信息工程班级1303班座号 16号姓名阮华朗日期2015.11.26实验五多态程序设计实验目的:1、理解运算符重载的概念和实质,掌握运算符重载函数的定义方法,掌握运算符重载为类的成员函数的方法。2、掌握虚函数的定义方法及其在实现多态性中的应用,理解静态连编和动态链编的区别。二、实验时间:2015年11月26号三、实验地点:福建工程学院北教1四、实验内容:1.已知基类:class Base{ public : virtual void iam(){cout”Base”endl;}}; 要求:(1)从Base类中派生出两个类,分别定义iam()函数,实现输出自己类名的功能。(2)main函数中完成两项操作:分别创建3个类的对象来调用iam()函数;定义3个类的对象指针,将指向派生类的对象的指针赋值给Base *指针,而后通过这些指针调用iam()函数。程序如下:#includeiostreamusing namespace std;class Base{public: virtual void iam() { coutBaseendl; }};class Base1:public Base{public: void iam() { coutBase1endl; }};class Base2:public Base{public: void iam() { coutBase2endl; }};int main(){ Base b; Base1 b1; Base2 b2; b.iam(); b1.iam(); b2.iam(); Base* p; p=b; p-iam(); p=b1; p-iam(); p=b2; p-iam(); return 0;}实验结果如下:实验结果分析:利用虚函数可以实现C++的多态,允许将子类类型的指针赋值给父类类型的指针,实现动态联编。2. 编写程序,写一个Shape抽象类,该类有求表面积(get_surface)和体积(get_volume)两个纯虚函数;由该类派生出圆柱体Cylinder,球体(Sphere),正方体(Cube),计算圆柱体,球体,正方体的表面积和体积。要求用抽象类实现。程序如下:#includeiostreamusing namespace std;class Shape{public: virtual void get_surface()=0; virtual void get_volume()=0;};class Cylinder:public Shape{public: Cylinder(double newR,double newH) { radius=newR; height=newH; } void get_surface() { coutThe surface of the Cylinder:3.14*2*radius*(radius+height)endl; } void get_volume() { coutThe volume of the Cylinder:3.14*radius*radius*heightendl; }private: double radius; double height;};class Sphere:public Shape{public: Sphere(double newR) { radius=newR; } void get_surface() { coutThe surface of the Sphere:4*3.14*radius*radiusendl; } void get_volume() { coutThe volume of the Sphere:4*3.14*radius*radius*radius/3.0endl; }private: double radius;};class Cube:public Shape{public: Cube(double newL) { length=newL; } void get_surface() { coutThe surface of the Cube:6

文档评论(0)

dashewan + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档