1 //#include <iostream>
2 //using namespace std;
3 //
4 //
5 //void main()
6 //{
7 // cin.get();
8 //}
9
10 #define _CRT_SECURE_NO_WARNINGS
11 #include <iostream>
12 using namespace std;
13
14 class father
15 {
16 public:
17 //虚函数表存放在首地址
18 virtual void go1()
19 {
20 cout << "go1" << endl;
21 }
22 virtual void go2()
23 {
24 cout << "go2" << endl;
25 }
26 virtual void go3()
27 {
28 cout << "go3" << endl;
29 }
30 };
31
32 class son :public father
33 {
34 public:
35
36 void go1()
37 {
38 cout << "son go1" << endl;
39 }
40
41 void go2()
42 {
43 cout << "son go2" << endl;
44 }
45
46 void go3()
47 {
48 cout << "son go3" << endl;
49 }
50 };
51
52 void main()
53 {
54 father *p = new son;
55 cout << sizeof(*p) << endl;
56 //对象的地址
57 cout << (void*)p << endl;
58 //虚函数表的地址
59 cout << (void*)(*((int *)p)) << endl;
60 //第一个元素的地址 类型转换->读内存->类型转换使得步长为4个字节
61 cout << (void*)( ((int *)*((int *)p) +0) ) << endl;
62
63 //取出函数表中的函数
64
65 auto fun1 = (void*)( *((int *)*((int *)p) + 0) );
66 auto fun2 = (void*)( *((int *)*((int *)p) + 1) );
67 auto fun3 = (void*)( *((int *)*((int *)p) + 2) );
68
69 typedef void(*P)();
70
71 //函数指针数组
72 P pfun[3];
73 pfun[0] = (P)fun1;
74 pfun[1] = (P)fun2;
75 pfun[2] = (P)fun3;
76
77 for (int i = 0; i < 3; i++)
78 {
79 pfun[i]();
80 }
81 cin.get();
82 }