chapter twelve 多态.ppt

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

第八章 多态性 本章主要内容 多态性 虚函数 纯虚函数 抽象类 8.1 多态性的概念 多态性是面向对象程序设计的重要特征之一。 多态性是指发出同样的消息被不同类型的对象接收时导致完全不同的行为。 消息——主要指对类的成员函数的调用。 多态的实现: 函数重载 运算符重载 虚函数----动态:运行时的多态 静态联编与动态联编 联编: 程序自身彼此关联的过程,确定程序中的操作调用与执行该操作的代码间的关系。 静态联编(静态束定) 联编工作出现在编译阶段,用对象名或者类名来限定要调用的函数。 动态联编 联编工作在程序运行时执行,在程序运行时才确定将要调用的函数。 #includeiostream.h class Point { public: Point(double i, double j) {x=i; y=j;} double Area( ) const{ return 0.0;} private: double x, y; }; class Rectangle:public Point { public: Rectangle(double i, double j, double k, double l); double Area( ) const {return w*h;} private: double w,h; }; Rectangle::Rectangle(double i, double j, double k, double l) :Point(i,j) { w=k; h=l; } void fun(Point s) { coutArea=s.Area( )endl; } void main( ) { Rectangle rec(3.0, 5.2, 15.0, 25.0); fun(rec); } 运行结果: Area=0 #includeiostream.h class Point { public: Point(double i, double j) {x=i; y=j;} virtual double Area( ) const{ return 0.0;} private: double x, y; }; class Rectangle:public Point { public: Rectangle(double i, double j, double k, double l); virtual double Area( ) const {return w*h;} private: double w,h; }; //其它函数同例 8.8 void fun(Point s) { coutArea=s.Area( )endl; } void main( ) { Rectangle rec(3.0, 5.2, 15.0, 25.0); fun(rec); } 运行结果: Area=375 8.3虚函数 虚函数是动态联编的基础。 是非静态的成员函数。 在类的声明中,在函数原型之前写virtual。 virtual 只用来说明类声明中的原型,不能用在函数实现时。 具有继承性,基类中声明了虚函数,派生类中无论是否说明,同原型函数都自动为虚函数。 本质:不是重载声明而是覆盖。 调用方式:通过基类指针或引用,执行时会 根据指针指向的对象的类,决定调用哪个函数。 例 8.4 #include iostream.h class B0 //基类B0声明 { public: //外部接口 virtual void display( ) {coutB0::display( )endl;} //虚成员函数 }; class B1: public B0 //公有派生 { public: void display( ) { coutB1::display( )endl; } }; class D1: public B1 //公有派生 { public: void display( ) { coutD1::display( )endl; } }; void fun(B0 *ptr) //普通函数 { ptr-display( ); } void main( ) //主函数 { B0 b0, *p; //声明基类对象和指针 B1 b1; //声明派生类对象 D1 d1; //声明派生类对象 p=b0; fun(p); //调用基类B0函数成员 p=b1; fun(p); //调用派生类B1函数成员 p=d

文档评论(0)

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

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

1亿VIP精品文档

相关文档