[C++] VTable测试

2019/09 10 17:09
 1 typedef unsigned int uint;
 2 typedef void (*callPtr)();
 3 
 4 class CBaseClass
 5 {
 6 public:
 7     CBaseClass(){}
 8     ~CBaseClass(){}
 9     virtual void Print()
10     {
11         printf("Call: CBaseClass Print\n");
12     }
13 };
14 
15 class CDeriveClass: public CBaseClass
16 {
17 public:
18     CDeriveClass(){}
19     ~CDeriveClass(){}
20     virtual void Print()
21     {
22         printf("Call: CDeriveClass Print\n");
23     }
24 };
25 
26 int main()
27 {
28     // 创建对象 pDeriveA
29     CBaseClass* pDeriveA= new CDeriveClass();
30     // 获得对象A的vtable
31     uint* pVTableA= (uint*)*((uint*)pDeriveA);
32     // 取得vtable中第0个function
33     callPtr funcA= (callPtr)pVTableA[0];
34     // 调用Print
35     funcA();
36 
37     // 创建对象 pDeriveB
38     CBaseClass* pDeriveB= new CDeriveClass();
39     // 获得对象B的vtable
40     uint* pVTableB= (uint*)*((uint*)pDeriveB);
41     // 2个对象的VTable应该相等
42     printf("vtable %s\n", (pVTableA== pVTableB) ? "Equal!" : "Not Equal!");
43 
44     return 0;
45 }
46