#include<iostream>
using namespace std;
class MyClass
{
public:
MyClass()
{
ma = 12;
mb = 32;
}
public :
int ma;
int mb;
};
int main()
{
MyClass mc;
MyClass * p = &mc;
//求出偏移量指针
int MyClass:: * pa = &MyClass::ma;
int MyClass:: * pb = &MyClass::mb;
void * pv = p;
unsigned char * pc = (unsigned char * )pv;
//求出偏移量数值
int nOffa = reinterpret_cast<int>(*(void**)(&pa));//将其转化为整型量。
int nOffb = reinterpret_cast<int>(*(void**)(&pb));//将其转化为整型量。
//加上偏移量
pc += (nOffb );
//求出该成员的值
int b = *(reinterpret_cast<int *>(pc));
pc = (unsigned char * )pv;
pc += (nOffa );
int a = *(reinterpret_cast<int *>(pc));
cout<<"a:"<<a<<endl;
cout<<"b:"<<b<<endl;
return 0;
}
//输出:
a:12
b:32通过偏移量来访问C++类数据成员实验,布布扣,bubuko.com
原文:http://blog.csdn.net/yyc1023/article/details/20153159