只有基类与派生类之间有多态的特性,意为多种形态(意味着调用成员函数时,会根据调用函数的对象的类型来执行不同的函数。)
class Shape { //基类protected:int width, height;public:Shape( int a=0, int b=0){width = a;height = b;}virtual int area(){cout << "Parent class area :" <<endl;return 0;}};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);}};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; //父类类型的指针=子类的对象// 调用矩形的求面积函数 areashape->area(); //实现覆盖父类方法// 存储三角形的地址shape = &tri;// 调用三角形的求面积函数 areashape->area();shape->Shape::area();return 0;}结果/*Rectangle class areaTriangle class areaParent class area*/
virtual告诉编译器在运行时才绑定对应类。而不是编译时就把area()绑定到Shape
只用把父子同名方法的父类方法声明虚函数即可
父类同名方法定义为虚函数后,此时父类方法已经被子类方法覆盖,若多态指针仍要访问父类被覆盖方法,在方法名前加上父类:: 类似java中的super
c++中多态分为静态多态和动态多态。
静态多态即重载(相同方法名靠参数列表区分)
动态多态即**不同对象调用同名函数**
