C++类之虚函数表和虚基类表及其内存布局(一个子类虚继承一个父类)

cpp 复制代码
#include<iostream>
class B
{
public:
	int b;

public:
	B(int i = 1) : b(i) {}
	virtual void f() { std::cout << "B::f()"; }
	virtual void Bf() { std::cout << "B::Bf()"; }
};

class B1 : virtual public B
{
public:
	int b1;

public:
	B1(int i = 100) :b1(i) {}
	virtual void f() { std::cout << "B1::f()"; }
	virtual void f1() { std::cout << "B1::f1()"; }
	virtual void B1f() { std::cout << "B1::B1f()"; }
};
int main()
{
	B1 a;
	std::cout << "B1对象内存大小为:" << sizeof(a) << std::endl;

	//取得B1的虚函数表
	std::cout << "[0]B1::vptr";
	std::cout << "\t地址:" << (int *)(&a) << std::endl;
	
	typedef void(*Fun)(void);

	//输出虚表B1::vptr中的函数
	for (int i = 0; i < 2; ++i)
	{
		std::cout << "  [" << i << "]";
		Fun fun1 = (Fun)*((int *)*(int *)(&a) + i);
		fun1();
		std::cout << "\t地址:" << *((int *)*(int *)(&a) + i) << std::endl;
	}

	//[1]
	std::cout << "[1]vbptr ";
	std::cout << "\t地址:" << (int *)(&a) + 1 << std::endl;  //虚表指针的地址
												 //输出虚基类指针条目所指的内容
	for (int i = 0; i < 2; i++)
	{
		std::cout << "  [" << i << "]";

		std::cout << *(int *)((int *)*((int *)(&a) + 1) + i);

		std::cout << std::endl;
	}


	//[2]
	std::cout << "[2]B1::ib1=" << *(int*)((int *)(&a) + 2);
	std::cout << "\t地址:" << (int *)(&a) + 2;
	std::cout << std::endl;

	//[3]
	std::cout << "[3]值=" << *(int*)((int *)(&a) + 3);
	std::cout << "\t\t地址:" << (int *)(&a) + 3;
	std::cout << std::endl;

	//[4]
	std::cout << "[4]B::vptr";
	std::cout << "\t地址:" << (int *)(&a) + 4 << std::endl;

	//输出B::vptr中的虚函数
	for (int i = 0; i < 2; ++i)
	{
		std::cout << "  [" << i << "]";
		Fun fun1 = (Fun)*((int *)*((int *)(&a) + 4) + i);
		fun1();
		std::cout << "\t地址:" << *((int *)*((int *)(&a) + 4) + i) << std::endl;
	}

	//[5]
	std::cout << "[5]B::ib=" << *(int*)((int *)(&a) + 5);
	std::cout << "\t地址:" << (int *)(&a) + 5;
	std::cout << std::endl;
}

验证结果:

参考文章
图说C++对象模型:对象内存布局详解

相关推荐
雾岛听蓝1 天前
Qt操作指南:窗口组成与菜单栏
开发语言·经验分享·笔记·qt
zopple1 天前
Laravel vs ThinkPHP:PHP框架终极对决
开发语言·php·laravel
松☆1 天前
C++ 算法竞赛题解:P13569 [CCPC 2024 重庆站] osu!mania —— 浮点数精度陷阱与 `eps` 的深度解析
开发语言·c++·算法
耿雨飞1 天前
Python 后端开发技术博客专栏 | 第 06 篇 描述符与属性管理 -- 理解 Python 属性访问的底层机制
开发语言·python
耿雨飞1 天前
Python 后端开发技术博客专栏 | 第 08 篇 上下文管理器与类型系统 -- 资源管理与代码健壮性
开发语言·python
(Charon)1 天前
【C++/Qt】C++/Qt 实现 TCP Server:支持启动监听、消息收发、日志保存
c++·qt·tcp/ip
2601_949194261 天前
Python爬虫完整代码拿走不谢
开发语言·爬虫·python
c***89201 天前
python爬虫——爬取全年天气数据并做可视化分析
开发语言·爬虫·python
aq55356001 天前
C语言、C++和C#:三大编程语言核心差异详解
java·开发语言·jvm
并不喜欢吃鱼1 天前
从零开始C++----七.继承及相关模型和底层(上篇)
开发语言·c++