随笔- 509  文章- 0  评论- 151  阅读- 22万 

2014-04-25 19:42

题目:C++中虚函数的工作原理?

解法:虚函数表?细节呢?要是懂汇编我就能钻的再深点了。我试着写了点测大小、打印指针地址之类的代码,能起点管中窥豹的作用,从编译器的外部感受下虚函数表、虚函数指针的存在。

代码:

复制代码
 1 // 13.3 How does virtual function works in C++?
 2 #include <cstring>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 class A {
 7 };
 8 
 9 class B {
10 public:
11     void f() {cout << "class B" << endl;};
12 };
13 
14 class C {
15 public:
16     C();
17 };
18 
19 class D {
20 public:
21     virtual void f() {
22         cout << "class D" << endl;
23     };
24 };
25 
26 class E: public D {
27 public:
28     void f() {
29         cout << "class E" << endl;
30     };
31 };
32 
33 int main()
34 {
35     D *ptr = new E();
36     D d;
37     E e;
38     unsigned ui;
39     
40     cout << sizeof(A) << endl;
41     cout << sizeof(B) << endl;
42     cout << sizeof(C) << endl;
43     cout << sizeof(D) << endl;
44     cout << sizeof(E) << endl;
45     // The result is 1 1 1 4 4 on Visual Studio 2012.
46     ptr->f();
47     // class with no data member have to occupy 1 byte, so as to have an address.
48     // class with virtual functions need a pointer to the virtual function table.
49     printf("The address of d is %p.\n", &d);
50     printf("The address of e is %p.\n", &e);
51     printf("The address of d.f is %p.\n", (&D::f));
52     printf("The address of e.f is %p.\n", (&E::f));
53 
54     memcpy(&ui, &d, 4);
55     printf("d = %X\n", ui);
56     memcpy(&ui, &e, 4);
57     printf("e = %X\n", ui);
58     memcpy(&ui, ptr, 4);
59     printf("*ptr = %X\n", ui);
60 
61     return 0;
62 }
复制代码

 

 posted on   zhuli19901106  阅读(171)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示