reinterpret_cast例子

本文通过一个C++示例介绍了如何使用reinterpret_cast进行类型转换,并展示了这种转换如何影响对象内存中的数据。同时,文章还探讨了虚函数表的位置及其大小对对象内存布局的影响。
#include <string>
#include <fstream>
using namespace std;

ofstream out("reinterp.out");

class X
{
	enum{sz = 5};
	int a[sz];
public:
	X()
	{
		memset(a, 0, sizeof(int) * sz);
	}
	virtual void f(){}
	int membsize()
	{
		return sizeof(a);
	}
	friend ostream& operator<<(ostream& os, const X& x)
	{
		for (int i = 0; i < sz; i++)
		{
			os << x.a[i] << ' ';
		}
		return os;
	}
};

int main()
{
	X x;
	out << x << endl;
	int* xp = reinterpret_cast<int*>(&x);
	xp[1] = 47;
	out << x << endl;

	X x2;
	const int vptr_size = sizeof(X) - x2.membsize();
	long l = reinterpret_cast<long>(&x2);
	l += vptr_size;
	xp = reinterpret_cast<int*>(l);
	xp[1] = 55;
	out << x2 << endl;

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值