class CFoo{
public:
int iBar1;
int iBar2;
int iBar3;
};
void main()
{
CFoo* pClass = NULL;//此处不需要new一个CFoo对象实例(只读不写)
int iFldKey1 = (long)(&(pClass->iBar1)) - (long)(pClass);
int iFldKey2 = (long)(&(pClass->iBar2)) - (long)(pClass);
int iFldKey3 = (long)(&(pClass->iBar3)) - (long)(pClass);
cout << "iFldKey1 : " << iFldKey1 << ", iFldKey2 : " << iFldKey2 << ", iFldKey3 : " << iFldKey3 << endl;
}
/*
运行结果:
iFldKey1 : 0, iFldKey2 : 4, iFldKey3 : 8
*/计算成员变量在对象中的偏移
最新推荐文章于 2021-05-16 23:31:21 发布
本文介绍了一种在C++中计算类成员变量在内存中偏移位置的方法,通过将指针转换为整数并相减的方式实现,适用于只读场景下的内存布局分析。
462

被折叠的 条评论
为什么被折叠?



