只有基类与派生类之间有多态的特性,意为多种形态(意味着调用成员函数时,会根据调用函数的对象的类型来执行不同的函数。)

    1. class Shape { //基类
    2. protected:
    3. int width, height;
    4. public:
    5. Shape( int a=0, int b=0)
    6. {
    7. width = a;
    8. height = b;
    9. }
    10. virtual int area()
    11. {
    12. cout << "Parent class area :" <<endl;
    13. return 0;
    14. }
    15. };
    16. class Rectangle: public Shape{
    17. public:
    18. Rectangle( int a=0, int b=0):Shape(a, b) { }
    19. int area ()
    20. {
    21. cout << "Rectangle class area :" <<endl;
    22. return (width * height);
    23. }
    24. };
    25. class Triangle: public Shape{
    26. public:
    27. Triangle( int a=0, int b=0):Shape(a, b) { }
    28. int area ()
    29. {
    30. cout << "Triangle class area :" <<endl;
    31. return (width * height / 2);
    32. }
    33. };
    34. // 程序的主函数
    35. int main( )
    36. {
    37. Shape *shape; //多肽类常用写法
    38. Rectangle rec(10,7);
    39. Triangle tri(10,5);
    40. // 存储矩形的地址
    41. shape = &rec; //父类类型的指针=子类的对象
    42. // 调用矩形的求面积函数 area
    43. shape->area(); //实现覆盖父类方法
    44. // 存储三角形的地址
    45. shape = &tri;
    46. // 调用三角形的求面积函数 area
    47. shape->area();
    48. shape->Shape::area();
    49. return 0;
    50. }
    51. 结果/*
    52. Rectangle class area
    53. Triangle class area
    54. Parent class area
    55. */

    virtual告诉编译器在运行时才绑定对应类。而不是编译时就把area()绑定到Shape
    只用把父子同名方法的父类方法声明虚函数即可

    父类同名方法定义为虚函数后,此时父类方法已经被子类方法覆盖,若多态指针仍要访问父类被覆盖方法,在方法名前加上父类:: 类似java中的super

    c++中多态分为静态多态和动态多态。
    静态多态即重载(相同方法名靠参数列表区分)
    动态多态即**不同对象调用同名函数**