c++语言程序设计(郑莉第四版)课件8.ppt
文本预览下载声明
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Complex operator + (const Complex c1, const Complex c2) { return Complex(c1.real + c2.real, c1.imag + c2.imag); } Complex operator - (Complex c1, Complex c2) { return Complex(c1.real - c2.real, c1.imag - c2.imag); } ostream operator (ostream out, const Complex c) { out ( c.real , c.imag ); return out; } * * 静态绑定与动态绑定 绑定 程序自身彼此关联的过程,确定程序中的操作调用与执行该操作的代码间的关系。 静态绑定 绑定过程出现在编译阶段,用对象名或者类名来限定要调用的函数。 动态绑定 绑定过程工作在程序运行时执行,在程序运行时才确定将要调用的函数。 #includeiostream using namespace std; class Point { public: Point(double x, double y) : x(x), y(y) { } double area() const { return 0.0; } private: double x, y; }; class Rectangle: public Point { public: Rectangle(double x, double y, double w, double h); double area() const { return w * h; } private: double w, h; }; 静态绑定例 * 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 Ba
显示全部