image.png

    虚函数(表)指针: vfptr
    v - virtual
    f - function
    ptr - pointer

    虚函数表:vftable
    v - virtual
    f - funciton
    table - table

    Animal类的speak不是虚函数的时候 类的布局是这样的
    image.png

    Animal类的speak是虚函数的时候 类的布局是这样的
    image.png

    Cat类继承Animal的speak不是虚函数的时候 Cat类的布局是这样的
    image.png
    Cat类继承Animal的speak是虚函数的时候 Cat类的布局是这样的
    image.png

    Cat类继承Animal的speak是虚函数的时候并且Cat类重写了虚函数时 Cat类的布局是这样的
    image.png

    总结:
    当父类中有虚函数时,父类内部会创建一个虚函数指针和一个虚函数表,指针指向虚函数表
    当子类继承父类时,子类会继承父类的虚函数指针和虚函数表,子类的虚函数指针指向父类的虚函数表
    当子类重写父类虚函数时,子类的虚函数指针会指向子类的虚函数表

    1. //多态
    2. //动物类
    3. class Animal
    4. {
    5. public:
    6. //虚函数
    7. //virtual void speak()
    8. //{
    9. // cout << "动物在说话" << endl;
    10. //}
    11. virtual void speak()
    12. {
    13. cout << "动物在说话" << endl;
    14. }
    15. };
    16. //猫类
    17. class Cat :public Animal
    18. {
    19. public:
    20. void speak()
    21. {
    22. cout << "小猫在说话" << endl;
    23. }
    24. };
    25. //狗类
    26. class Dog :public Animal
    27. {
    28. public:
    29. void speak()
    30. {
    31. cout << "小狗在说话" << endl;
    32. }
    33. };
    34. //执行说话的函数
    35. //地址早绑定 在编译阶段确定函数地址
    36. //如果想执行让猫说话,那么这个函数地址就不能提前绑定,需要在运行阶段进行绑定,地址晚绑定
    37. //动态多态满足条件
    38. // 1、有继承关系
    39. // 2、子类重写父类中的虚函数
    40. //动态多态使用
    41. // 父类的指针或者引用 指向子类对象
    42. //函数重写:函数返回值类型 函数名 参数列表完全相同
    43. void doSpeak(Animal& animal) //Animal & animal = cat;
    44. {
    45. animal.speak();
    46. }
    47. void test01()
    48. {
    49. Cat cat;
    50. doSpeak(cat);
    51. Dog dog;
    52. doSpeak(dog);
    53. }
    54. void test02()
    55. {
    56. cout << "sizeof Animal = " << sizeof(Animal) << endl;
    57. }
    58. int main()
    59. {
    60. //test01();
    61. test02();
    62. system("pause");
    63. return 0;
    64. }