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 ;
}

最新文章

  1. C# Session添加、删除封装类
  2. 三年回首:C基础
  3. css 设置圆角
  4. duplicate symbols for architecture armv7解决办法
  5. 题目1005:Graduate Admission
  6. 【源码】基于SQLite实现CMS论坛(BBS)----附件SQLite可视化界面客户端
  7. contiki makefile框架分析 &lt; contiki学习之一 &gt;
  8. Top 100 English Verbs
  9. 梳理一下重装sql2008R2sp1步骤
  10. Xcode8.3.2制作静态库
  11. 深入理解Oracle中的随机函数
  12. MYSQL数据库的设计与调优
  13. 兄弟连学python---Socket介绍
  14. node 相关网站
  15. js点击空白处触发事件
  16. [na]ip包格式
  17. VUE系列二:vue基础
  18. layer,一个可以让你想到即可做到的javascript弹窗(层)解决方案
  19. git如何列出分支之间的差异commit
  20. 工具:SVN的Web客户端(ViewVC、SVNWebClient、sventon)和任务管理(Trac、Collaboa)

热门文章

  1. 如何利用PHP语言压缩图片?PHP入门教程
  2. PHP文件是什么?如何打开PHP文件?
  3. ARM实验2 —— 蜂鸣器实验
  4. POST信息模拟登录获取页面内容
  5. python_2_变量的使用2
  6. lasagne保存网络参数
  7. 二、OC的构造方法和descriprtion方法
  8. 初尝微信小程序2-基本框架
  9. ios数据持久化--CoreData框架的介绍和使用
  10. 太阳地球月亮运行动画(使用@keyframes)