文档详情

C++语言程序设计(学习课件)08(精品)解析.ppt

发布:2017-01-08约1.17万字共54页下载文档
文本预览下载声明
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 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的结果是
显示全部
相似文档