C++ 虚函数表与多态 —— 使用继承 & 多重继承的虚函数表

1. 使用继承的虚函数表:

每个类只有1个虚函数表,当子类继承父类后,子类可以自己改写和新增虚函数,如下图所示:

 

子类重写 func_1 后,子函数的 func_1 将会有新的逻辑,不会干扰到父类;

子类新增行的 func_4 方法后,父类无法访问到该方法。

如下代码:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Father
 5 {
 6 public:
 7     virtual void func_1() { cout << "Father::func_1" << endl; }
 8     virtual void func_2() { cout << "Father::func_2" << endl; }
 9     virtual void func_3() { cout << "Father::func_3" << endl; }
10 public:
11     int x = 666;
12     int y = 999;
13 };
14 
15 class Son : public Father
16 {
17 public:
18     void func_1() { cout << "Son::func_1" << endl; }                //重写了虚函数
19     virtual void func_4() { cout << "Son::func_4" << endl; }        //子类对象新写的虚函数 func_4
20 };
21 
22 typedef void(*func_t)(void);
23 
24 int main(void)
25 {
26     Father father;
27     cout << "father 对象地址:" << (int*)&father << endl;
28     int* vptr_f = (int*)*(int*)&father;
29     for (int i = 0; i < 3; i++)                //这里如果想循环4次往下访问,不会访问到子类的 func_4 ,会访问到非法内存
30     {
31         cout << "调用第" << i + 1 << "个虚函数:";
32         ((func_t) * (vptr_f + i))();
33     }
34 
35     cout << "============================================" << endl;
36 
37     Son son;
38     cout << "son 对象地址:" << (int*)&son << endl;
39     int* vptr_s = (int*)*(int*)&son;
40 
41     for (int i = 0; i < 4; i++)
42     {
43         cout << "调用第" << i + 1 << "个虚函数:";
44         ((func_t) * (vptr_s + i))();
45     }
46 
47     for (int i = 0; i < 2; i++)
48     {
49         cout << *(int*)((int)&son + 4 + i * 4) << endl;
50     }
51     cout << "sizof(son)==" << sizeof(son) << endl;
52 }

运行结果:

father 对象地址:0039FA70
调用第1个虚函数:Father::func_1
调用第2个虚函数:Father::func_2
调用第3个虚函数:Father::func_3
============================================
son 对象地址:0039FA44
调用第1个虚函数:Son::func_1
调用第2个虚函数:Father::func_2
调用第3个虚函数:Father::func_3
调用第4个虚函数:Son::func_4
666
999
sizof(son)==12

2. 多重继承的虚函数表:

===========================================================================================================

猜你喜欢

转载自www.cnblogs.com/CooCoChoco/p/12556468.html