通过偏移量来访问C++类数据成员实验

#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

通过偏移量来访问C++类数据成员实验

上一篇:Linux C++ read 和 write,open 函数的使用


下一篇:python多线程