https://blog.csdn.net/xuebing1995/article/details/103695355

多态按字面的意思就是多种形态。当类之间存在层次结构,并且类之间是通过继承关联时,就会用到多态。
C++ 多态意味着调用成员函数时,会根据调用函数的对象的类型来执行不同的函数。

静态多态

  1. #include <iostream>
  2. using std::cout;
  3. using std::endl;
  4. class Shape {
  5. public:
  6. Shape(int width, int height) : width(width), height(height) {}
  7. int area() {
  8. cout << "Parent class area" << endl;
  9. }
  10. protected:
  11. int width;
  12. int height;
  13. };
  14. class Tri : public Shape {
  15. public:
  16. Tri(int width, int height) : Shape(width, height) {}
  17. int area() {
  18. cout << "Tri class area :" << endl;
  19. return (width * height);
  20. }
  21. };
  22. class Rect : public Shape {
  23. public:
  24. Rect(int width, int height) : Shape(width, height) {}
  25. int area() {
  26. cout << "Rect class area :" << endl;
  27. return (width * height);
  28. }
  29. };
  30. int main() {
  31. Shape *shape;
  32. Rect i = Rect(2, 3);
  33. shape = &i;
  34. shape->area();
  35. Tri j = Tri(1, 3);
  36. shape = &j;
  37. shape->area();
  38. return 0;
  39. }
  40. //Parent class area
  41. //Parent class area

控制台和预期输出不符,调用函数 area() 被编译器设置为基类中的版本,这就是所谓的静态多态,或静态链接 - 函数调用在程序执行前就准备好了。有时候这也被称为早绑定,因为 area() 函数在程序编译期间就已经设置好了。

动态多态

  1. class Shape {
  2. public:
  3. Shape(int width, int height) : width(width), height(height) {}
  4. virtual int area() {
  5. cout << "Parent class area" << endl;
  6. }
  7. protected:
  8. int width;
  9. int height;
  10. };
  11. //Rect class area :
  12. //Tri class area :

虚函数实现的多态。此时,编译器看的是指针的内容,而不是它的类型。因此,由于 tri 和 rec 类的对象的地址存储在 shape 中,所以会调用各自的 area() 函数。
正如所看到的,每个子类都有一个函数 area() 的独立实现。这就是*多态的一般使用方式
。有了多态,您可以有多个不同的类,都带有同一个名称但具有不同实现的函数,函数的参数甚至可以是相同的。

如果某一个子类没有实现,则会继续调用父类的

  1. class Shape {
  2. public:
  3. Shape(int width, int height) : width(width), height(height) {}
  4. virtual int area() {
  5. cout << "Parent class area" << endl;
  6. return 0;
  7. }
  8. protected:
  9. int width;
  10. int height;
  11. };
  12. class Tri : public Shape {
  13. public:
  14. Tri(int width, int height) : Shape(width, height) {}
  15. // int area() {
  16. // cout << "Tri class area :" << endl;
  17. // return (width * height);
  18. // }
  19. };
  20. class Rect : public Shape {
  21. public:
  22. Rect(int width, int height) : Shape(width, height) {}
  23. int area() {
  24. cout << "Rect class area :" << endl;
  25. return (width * height);
  26. }
  27. };
  28. //Rect class area :
  29. //Parent class area

虚函数

虚函数 是在基类中使用关键字 virtual 声明的函数。在派生类中重新定义基类中定义的虚函数时,会告诉编译器不要静态链接到该函数。
我们想要的是在程序中任意点可以根据所调用的对象类型来选择调用的函数,这种操作被称为动态链接,或后期绑定。

纯虚函数

您可能想要在基类中定义虚函数,以便在派生类中重新定义该函数更好地适用于对象,但是您在基类中又不能对虚函数给出有意义的实现,这个时候就会用到纯虚函数。

  1. class Shape {
  2. public:
  3. Shape(int width, int height) : width(width), height(height) {}
  4. virtual int area() = 0;
  5. protected:
  6. int width;
  7. int height;
  8. };

派生类必须实现此函数的覆盖