《Cracking the Coding Interview》——第13章:C和C++——题目3
2024-09-04 17:59:46
2014-04-25 19:42
题目:C++中虚函数的工作原理?
解法:虚函数表?细节呢?要是懂汇编我就能钻的再深点了。我试着写了点测大小、打印指针地址之类的代码,能起点管中窥豹的作用,从编译器的外部感受下虚函数表、虚函数指针的存在。
代码:
// 13.3 How does virtual function works in C++?
#include <cstring>
#include <iostream>
using namespace std; class A {
}; class B {
public:
void f() {cout << "class B" << endl;};
}; class C {
public:
C();
}; class D {
public:
virtual void f() {
cout << "class D" << endl;
};
}; class E: public D {
public:
void f() {
cout << "class E" << endl;
};
}; int main()
{
D *ptr = new E();
D d;
E e;
unsigned ui; cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
cout << sizeof(C) << endl;
cout << sizeof(D) << endl;
cout << sizeof(E) << endl;
// The result is 1 1 1 4 4 on Visual Studio 2012.
ptr->f();
// class with no data member have to occupy 1 byte, so as to have an address.
// class with virtual functions need a pointer to the virtual function table.
printf("The address of d is %p.\n", &d);
printf("The address of e is %p.\n", &e);
printf("The address of d.f is %p.\n", (&D::f));
printf("The address of e.f is %p.\n", (&E::f)); memcpy(&ui, &d, );
printf("d = %X\n", ui);
memcpy(&ui, &e, );
printf("e = %X\n", ui);
memcpy(&ui, ptr, );
printf("*ptr = %X\n", ui); return ;
}
最新文章
- C# Session添加、删除封装类
- 三年回首:C基础
- css 设置圆角
- duplicate symbols for architecture armv7解决办法
- 题目1005:Graduate Admission
- 【源码】基于SQLite实现CMS论坛(BBS)----附件SQLite可视化界面客户端
- contiki makefile框架分析 <; contiki学习之一 >;
- Top 100 English Verbs
- 梳理一下重装sql2008R2sp1步骤
- Xcode8.3.2制作静态库
- 深入理解Oracle中的随机函数
- MYSQL数据库的设计与调优
- 兄弟连学python---Socket介绍
- node 相关网站
- js点击空白处触发事件
- [na]ip包格式
- VUE系列二:vue基础
- layer,一个可以让你想到即可做到的javascript弹窗(层)解决方案
- git如何列出分支之间的差异commit
- 工具:SVN的Web客户端(ViewVC、SVNWebClient、sventon)和任务管理(Trac、Collaboa)