本文主要是介绍通过偏移量来访问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++类数据成员实验的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!