前言

虚函数执行速度要稍慢一些。为了实现多态性,每一个派生类中均要保存相应虚函数的入口地址表,函数的调用机制也是间接实现。所以多态性总是要付出一定代价,但通用性是一个更高的目标。

实验环境

Windows10 企业版

Visual Studio2017 15.8.1

引入虚函数后内存大小变

没有虚函数时类占用内存大小

#include<iostream>
using namespace std; class Base
{
public:
Base()
{
cout << "Create Base" << endl;
}
~Base()
{
cout << "Free Base" << endl;
}
public:
void Show()
{
cout << "This is Base Show()" << endl;
}
private:
int x;
}; void main()
{
cout << sizeof(Base) << endl;
Base b;
}

占用内存为4字节。在x86 模式下,整形变量大小为4字节

有虚函数时类占用内存大小

#include<iostream>
using namespace std; class Base
{
public:
Base()
{
cout << "Create Base" << endl;
}
~Base()
{
cout << "Free Base" << endl;
}
public:
virtual void Show()
{
cout << "This is Base Show()" << endl;
}
private:
int x;
}; void main()
{
cout << sizeof(Base) << endl;
Base b;
}

占用内存为8字节。在x86 模式下,整形变量大小为4字节。剩下4字节是虚函数表指针,指针变量在x86下占内存大小4字节。

代码中只定义了一个虚函数,定义多个虚函数,类的大小还是8。虚函数表的指针指向的是虚函数表的入口地址

虚函数表

 #include<iostream>
using namespace std; class Base
{
public:
Base()
{
cout << "Create Base" << endl;
}
~Base()
{
cout << "Free Base" << endl;
}
public:
virtual void Show()
{
cout << "This is Base Show()" << endl;
}
virtual void Print()
{
cout << "This is Base Print()" << endl;
}
void Fun()
{
cout << "This is Base Fun()" << endl;
}
private:
int x;
}; class D :public Base
{
public:
D()
{}
~D()
{}
public:
void Show()
{
cout << "This is D Show()" << endl;
}
void Fun()
{
cout << "This is D Fun()" << endl;
}
virtual void List()
{
cout << "This is D List()" << endl;
}
private:
int y;
}; void main()
{
D d;
}

虚函数表前后变化

虚函数表在构造父类的时候会记录所有父类的虚函数

这里面少显示了子类的List虚方法,少显示是编译器的问题。但是你不能通过父类指针访问子类List()方法,因为List超出了父类范围。

子类构造完成后,子类重写了父类的虚函数,虚函数表中的虚函。数就变成了子类的。狸猫混太子,偷梁换柱的意思

最新文章

  1. Win8.1想要卸载openSUSE出现问题(2014.8.15已解决)
  2. 在linux系统下怎么安装两个nginx
  3. hdu5136:组合计数、dp
  4. ASP.NET PipeLine #Reprinted#
  5. 前端自动化部署之gulp
  6. HDU 5900
  7. IIS ApplicationPoolIdentity(配置IIS讀寫網站文件)
  8. Android全屏截图的方法,返回Bitmap并且保存在SD卡上
  9. Python笔记-IO编程
  10. python经典书籍推荐:Python核心编程
  11. Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded
  12. echarts设置option中的数据对象优化
  13. Android--Service之AIDL传递复杂对象
  14. hive 限制本地内存使用量
  15. [UWP]在UWP平台中使用Lottie动画
  16. Netstat Commands for Linux Network Management
  17. 【python】bytes与字符串的相互转化
  18. C语言 &#183; 高精度乘法
  19. (转)基于DDD的现代ASP.NET开发框架--ABP分层架构
  20. javaweb Servlet接收Android请求,并返回json数据

热门文章

  1. Python - Django - 模板语言之 Tags(标签)
  2. rename批量命名命令
  3. Web书写Test Case时需要考虑的检查点
  4. python 多线程模板简单实现
  5. Mac下WordPress4.1安装使用笔记
  6. 一文带你全面了解RxJava
  7. qt qml Treeview使用记录--设置每个Item的图片logo,高度
  8. redis 那些事儿
  9. LeetCode 20. 有效的括号(Valid Parentheses)
  10. Quartz.Net—配置化