多态
#include <iostream> using namespace std; // 基类 Shape class Shape { protected: int width, height; public: // 构造方法 Shape(int a = 0, int b = 0) { width = a; height = b; } /*这里如果不加virtual关键,就是静态多态,也就是"早绑定", 这样所有派生类在调用这个方法时执行的都是基类的这个方法, 而如果加上这个关键字,就是动态链接,或者叫"后期绑定",这样所有派生类在调用这个方法的时候, 就会执行各自的这个方法,虽然函数名相同,但是各自实现的功能是不同的,这就是"多态"! */ virtual int area() { cout << "Parent class area :" << endl; return 0; } }; // 派生类 Rectangle class Rectangle : public Shape { public: Rectangle(int a = 0, int b = 0) :Shape(a, b) { } // 表示调用父类的构造方法 int area() { cout << "Rectangle class area :" << endl; return (width * height); } }; // 派生类 Triangle class Triangle : public Shape { public: Triangle(int a = 0, int b = 0) :Shape(a, b) { } // 表示调用父类的构造方法 int area() { cout << "Triangle class area :" << endl; return (width * height / 2); } }; // 程序的主函数 int main() { Shape *shape; // 对象指针 Rectangle rec(10, 7); // 调用构造 Triangle tri(10, 5); // 存储矩形的地址 shape = &rec; // 调用矩形的求面积函数 area int rec_area = shape->area(); // 调用的是同样的方法,返回的却是各自的数据 cout << "rec_area = " << rec_area << endl; // 存储三角形的地址 shape = &tri; // 调用三角形的求面积函数 area int tri_area = shape->area(); // 调用的是同样的方法,返回的却是各自的数据 cout << "tri_area = " << tri_area << endl; system("pause"); return 0; }
运行: