C++语言程序设计(清华大学郑莉)八知识汇总.ppt

C++语言程序设计(清华大学郑莉)八知识汇总.ppt

  1. 1、本文档共54页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Rectangle::Rectangle(double x, double y, double w, double h) :Point(x, y), w(w), h(h) { } void fun(const Point s) { cout Area = s.area() endl; } int main() { Rectangle rec(3.0, 5.2, 15.0, 25.0); fun(rec); return 0; } 运行结果: Area = 0 * #includeiostream using namespace std; class Point { public: Point(double x, double y) : x(x), y(y) { } virtual double area() const { return 0.0; } private: double x, y; }; class Rectangle:public Point { public: Rectangle(double x, double y, double w, double h); virtual double area() const { return w * h; } private: double w, h; }; //其他函数同上例 动态绑定例 * void fun(const Point s) { cout Area = s.area() endl; } int main() { Rectangle rec(3.0, 5.2, 15.0, 25.0); fun(rec); return 0; } 运行结果: Area = 375 * * 虚函数 虚函数是动态绑定的基础。 是非静态的成员函数。 在类的声明中,在函数原型之前写virtual。 virtual 只用来说明类声明中的原型,不能用在函数实现时。 具有继承性,基类中声明了虚函数,派生类中无论是否说明,同原型函数都自动为虚函数。 本质:不是重载声明而是覆盖。 调用方式:通过基类指针或引用,执行时会 根据指针指向的对象的类,决定调用哪个函数。 虚 函 数 * 例 8-4 #include iostream using namespace std; class Base1 { //基类Base1定义 public: virtual void display() const; //虚函数 }; void Base1::display() const { cout Base1::display() endl; } class Base2: public Base1 { //公有派生类Base2定义 public: void display() const; //覆盖基类的虚函数 }; void Base2::display() const { cout Base2::display() endl; } 虚 函 数 //公有派生类Derived定义 class Derived: public Base2 { public: void display() const; //覆盖基类的虚函数 }; void Derived::display() const { cout Derived::display() endl; } //参数为指向基类对象的指针 void fun(Base1 *ptr) { ptr-display(); //对象指针-成员名 } * int main() { //主函数 Base1 base1; //定义Base1类对象 Base2 base2; //定义Base2类对象 Derived derived; //定义Derived类对象 fun(base1); //用Base1对象的指针调用fun函数 fun(base2); //用Base2对象的指针调用fun函数 fun(derived); //用Derived对象的指针调用fun函数 return 0; } 运行结果: Base1::display() Base2::display() Derived::display() * * 虚析构函数 为什么需要虚析构函数? 可能通过基类指针删除派生类对象; 如果你打算允许其他人通过基类指针调用对象的析构函数(通过delete这样做是正常的),就需要让基类的析构函数成为虚函数,否则执行delete的结果是

文档评论(0)

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

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

1亿VIP精品文档

相关文档