#include using namespace std; class Shape { protected: int width, height; public: Shape(int a, int b) { width = a; height = b; } int area() { cout << "Parent class area :" <area() -----" << endl; cout << shape->area() << endl; // 调用矩形的求面积函数 area // 如果使用变量,执行的是派生类Rectangle的方法。 cout << "----- rec.area() -----" << endl; cout << rec.area() << endl; // 可以在通过派生类的变量rec,调用基类的方法 // 调用方法是<派生类变量>.<基类类名>::<基类方法> cout << "----- rec.Shape::area() -----" << endl; cout << rec.Shape::area() << endl; // 我们想要的是在程序中任意点可以根据所调用的对象类型来选择调用的函数 // 这种操作被称为动态链接,或后期绑定。 cout << "----- shape->virtualArea() -----" << endl; cout << shape->virtualArea() << endl; // 通过纯虚函数的实现,来执行派生类的方法 cout << "----- shape->pureVirtualArea() -----" << endl; cout << shape->pureVirtualArea() << endl; // 存储三角形的地址 shape = &tri; // 调用三角形的求面积函数 area // shape是基类的指针,使用基类指针调用函数 area() ,执行的是基类Shape的方法。 // 这就是所谓的静态多态,或静态链接调用函数。 cout << "----- shape->area() -----" << endl; cout << shape->area() << endl; // 调用三角形的求面积函数 area // 如果使用变量,执行的是派生类Triangle的方法。 cout << "----- tri.area() -----" << endl; cout << tri.area() << endl; // 可以在通过派生类的变量tri,调用基类的方法 // 调用方法是<派生类变量>.<基类类名>::<基类方法> cout << "----- tri.Shape::area() -----" << endl; cout << tri.Shape::area() << endl; // 我们想要的是在程序中任意点可以根据所调用的对象类型来选择调用的函数 // 这种操作被称为动态链接,或后期绑定。 cout << "----- shape->virtualArea() -----" << endl; cout << shape->virtualArea() << endl; // 通过纯虚函数的实现,来执行派生类的方法 cout << "----- shape->pureVirtualArea() -----" << endl; cout << shape->pureVirtualArea() << endl; return 0; }