C++——多态实现原理分析
2024-08-26 22:17:35
前言
虚函数执行速度要稍慢一些。为了实现多态性,每一个派生类中均要保存相应虚函数的入口地址表,函数的调用机制也是间接实现。所以多态性总是要付出一定代价,但通用性是一个更高的目标。
实验环境
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超出了父类范围。
子类构造完成后,子类重写了父类的虚函数,虚函数表中的虚函。数就变成了子类的。狸猫混太子,偷梁换柱的意思
最新文章
- Win8.1想要卸载openSUSE出现问题(2014.8.15已解决)
- 在linux系统下怎么安装两个nginx
- hdu5136:组合计数、dp
- ASP.NET PipeLine #Reprinted#
- 前端自动化部署之gulp
- HDU 5900
- IIS ApplicationPoolIdentity(配置IIS讀寫網站文件)
- Android全屏截图的方法,返回Bitmap并且保存在SD卡上
- Python笔记-IO编程
- python经典书籍推荐:Python核心编程
- 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
- echarts设置option中的数据对象优化
- Android--Service之AIDL传递复杂对象
- hive 限制本地内存使用量
- [UWP]在UWP平台中使用Lottie动画
- Netstat Commands for Linux Network Management
- 【python】bytes与字符串的相互转化
- C语言 &#183; 高精度乘法
- (转)基于DDD的现代ASP.NET开发框架--ABP分层架构
- javaweb Servlet接收Android请求,并返回json数据