虚函数表
1 /* 虚函数原理 */
2
3 #include<iostream>
4
5 using namespace std;
6
7 class myclass
8 {
9 public:
10 virtual void go1()
11 {
12 cout << "virtual void go1" << endl;
13 }
14
15 virtual void go2()
16 {
17 cout << "virtual void go2" << endl;
18 }
19
20 virtual void go3()
21 {
22 cout << "virtual void go3" << endl;
23 }
24
25 };
26
27 class erziclass : public myclass
28 {
29 public:
30 void go1()
31 {
32 cout << "void go1" << endl;
33 }
34
35 void go2()
36 {
37 cout << "void go2" << endl;
38 }
39
40 };
41
42
43 void main()
44 {
45 myclass *p = new myclass;
46
47 cout << sizeof(*p) << endl;
48
49 cout << (int*)p << endl;// 打印虚函数表地址的地址
50
51 cout << *((int*)p) << endl;// 打印已是虚函数表的地址
52
53 cout << (void *)(*((int*)p)) << endl;// 转换为(void*)打印虚函数表的地址
54
55
56 cout << (void *)(*((int *)*((int*)p)+0)) << endl;// 虚函数地址
57 cout << (void *)(*((int *)*((int*)p)+1)) << endl;
58 cout << (void *)(*((int *)*((int*)p)+2)) << endl;
59
60 auto p1 = (void *)(*((int *)*((int*)p)+0));
61 auto p2 = (void *)(*((int *)*((int*)p)+1));
62 auto p3 = (void *)(*((int *)*((int*)p)+2));
63
64
65 typedef void(*FUN)();
66
67 FUN fun1 = (FUN)p1;// 定义函数指针访问虚函数表地址
68 (fun1)();
69 FUN X[3];
70 for (int i=0;i<3;i++)
71 {
72 X[i] = (FUN)(void *)(*((int *)*((int*)p)+i))
73 X[i]();// 调用
74 }
75
76
77 // void(myclass::*pgo1)() = &myclass::go1;// pgo1是一个函数指针
78 // auto p1 = &myclass::go1;
79 // cout << "go1地址 = " << (void *)pgo1 << endl;
80
81 cin.get();
82 }
83
84
85 // ------------------------------------------------------------------
86
87 void main()
88 {
89 myclass *p = new erzimyclass;
90
91 cout << sizeof(*p) << endl;
92
93 cout << (int*)p << endl;// 打印虚函数表地址的地址
94
95 cout << *((int*)p) << endl;// 打印已是虚函数表的地址
96
97 cout << (void *)(*((int*)p)) << endl;// 转换为(void*)打印虚函数表的地址
98
99
100 cout << (void *)(*((int *)*((int*)p)+0)) << endl;// 虚函数地址
101 cout << (void *)(*((int *)*((int*)p)+1)) << endl;
102 cout << (void *)(*((int *)*((int*)p)+2)) << endl;
103
104 auto p1 = (void *)(*((int *)*((int*)p)+0));
105 auto p2 = (void *)(*((int *)*((int*)p)+1));
106 auto p3 = (void *)(*((int *)*((int*)p)+2));
107
108
109 typedef void(*FUN)();
110
111 FUN fun1 = (FUN)p1;// 定义函数指针访问虚函数表地址
112 (fun1)();
113 FUN X[3];
114 for (int i=0;i<3;i++)
115 {
116 X[i] = (FUN)(void *)(*((int *)*((int*)p)+i))
117 X[i]();// 调用
118 }
119
120
121 // void(myclass::*pgo1)() = &myclass::go1;// pgo1是一个函数指针
122 // auto p1 = &myclass::go1;
123 // cout << "go1地址 = " << (void *)pgo1 << endl;
124
125 cin.get();
126 }
127
128 // 虚函数表 工作中基本不用
129 // 面试的时候用的最多属于编译原理
130 // 理解二级函数指针 指针类型转换 跳过私有直接操作函数
长风破浪会有时,直挂云帆济沧海
posted on 2015-06-10 15:09 Dragon-wuxl 阅读(137) 评论(0) 收藏 举报
浙公网安备 33010602011771号