Structure, function, class offset

1. Structure offset

struct Test{
    
    
	int a;//4byte
	int b;//4byte
	int c;
	int d;
	}
	//a->d 低到高

//这俩在内存中的结构是一样的
Test test;
int  arrtest[4];
//
int Test::*memoffset=&Test::a;
cout<<"Show the offset"<<endl;
printf("a's offset %u \n",memoffset);//对照test的起始地址偏移0位
memoffset=&Test::b;
printf("b's offset %u \n",memoffset);//4
memoffset=&Test::c;
printf("c's offset %u \n",memoffset);//8
memoffset=&Test::d;
printf("d's offset %u \n",memoffset);//12

//我们通常使用点语法访问a
int t=test.a;
//但是当我们知道内存布局偏移后就可以使用指针访问
int *membegin=(int *)&test;
//点语法和int b指针取法在机器码下完全一样
test.b=110;
int b=*(membegin+1);//以membegin的类型int长度为基数单位,所以+1
printf("b is %d",b);

//演示一下怎么一样
int *pointer=&arrtest[0];//pointer指向arrtest的首地址
//将arrtesst的首地址给了testarr
Test* testarr=(Test*)pointer;//强行将pointer转换成test
testarr->a=1;
testarr->b=2;
printf("a is %d,b is %d",arrtest[0],arrtest[1]);

//接下来顺路解释下联合体union
size_t offset=(size_t)memoffset;//无法转换
//使用union可以
union{
    
    
	size_t offset;
	int Test::* offsetT;
	}offsetu;
offsetu.offsetT=&Test::a;
size_t offsetA=offsetu.offset;
printf("offsetA is %u ",offsetA);


Guess you like

Origin blog.csdn.net/guanxunmeng8928/article/details/109527884