代码改变世界

c++对象中的成员变量地址分布

2012-04-08 19:15  江上渔者  阅读(609)  评论(0编辑  收藏  举报
 1 // 指针.cpp : 定义控制台应用程序的入口点。
2 //
3
4 #include "stdafx.h"
5 #include<iostream>
6 using namespace std;
7
8 /*
9 *(1)对象大小大于等于所有成员变量大小之和;
10 *(2)成员变量地址与对象地址的差必须能被成员变量大小整除;
11 *(3)默认情况下成员变量地址按定义先后紧凑分布。
12 */
13
14 // 结构体中成员变量地址与对象地址的关系
15 int GetAddress(int iObject, int iPrev, int iSizeOfPrev, int iSizeOfCurr)
16 {
17 int iCurr = iPrev + iSizeOfPrev; // 前一个成员变量地址值加上前一个成员变量大小
18 int iCurrRelative = iCurr - iObject; // 与对象地址的相对值
19 if (iCurrRelative % iSizeOfCurr != 0) // 相对值不为整数倍
20 iCurr += iSizeOfCurr - (iCurrRelative % iSizeOfCurr); // 补上差值
21 return iCurr;
22 }
23
24 int _tmain(int argc, _TCHAR* argv[])
25 {
26 typedef char t1;
27 typedef short int t2;
28 typedef char t3;
29 typedef int t4;
30 typedef double t5;
31 typedef short int t6;
32 typedef float t7;
33
34 char a;
35 struct S{t1 m1;t2 m2;t3 m3;t4 m4;t5 m5;t6 m6;t7 m7;};
36 S s1;
37 cout<<"s1的大小:"<<sizeof(S)<<endl;
38 cout<<"直接访问s1中的每个成员:"<<endl;
39 cout<<"&s1\t=\t"<<(void*)(&s1)<<endl;
40 cout<<"&m1\t=\t"<<(void*)(&s1.m1)<<endl;
41 cout<<"&m2\t=\t"<<(void*)(&s1.m2)<<endl;
42 cout<<"&m3\t=\t"<<(void*)(&s1.m3)<<endl;
43 cout<<"&m4\t=\t"<<(void*)(&s1.m4)<<endl;
44 cout<<"&m5\t=\t"<<(void*)(&s1.m5)<<endl;
45 cout<<"&m6\t=\t"<<(void*)(&s1.m6)<<endl;
46 cout<<"&m7\t=\t"<<(void*)(&s1.m7)<<endl;
47
48 int is1 = (int)(&s1);
49 // 通过ps1访问s1中的每个成员
50 t1 *pm1 = (t1*)(is1);
51 t2 *pm2 = (t2*)(GetAddress(is1,(int)pm1,sizeof(t1),sizeof(t2)));
52 t3 *pm3 = (t3*)(GetAddress(is1,(int)pm2,sizeof(t2),sizeof(t3)));
53 t4 *pm4 = (t4*)(GetAddress(is1,(int)pm3,sizeof(t3),sizeof(t4)));
54 t5 *pm5 = (t5*)(GetAddress(is1,(int)pm4,sizeof(t4),sizeof(t5)));
55 t6 *pm6 = (t6*)(GetAddress(is1,(int)pm5,sizeof(t5),sizeof(t6)));
56 t7 *pm7 = (t7*)(GetAddress(is1,(int)pm6,sizeof(t6),sizeof(t7)));
57 cout<<"通过ps1访问s1中的每个成员:"<<endl;
58 cout<<"pm1\t=\t"<<(void*)(pm1)<<endl;
59 cout<<"pm2\t=\t"<<(void*)(pm2)<<endl;
60 cout<<"pm3\t=\t"<<(void*)(pm3)<<endl;
61 cout<<"pm4\t=\t"<<(void*)(pm4)<<endl;
62 cout<<"pm5\t=\t"<<(void*)(pm5)<<endl;
63 cout<<"pm6\t=\t"<<(void*)(pm6)<<endl;
64 cout<<"pm7\t=\t"<<(void*)(pm7)<<endl;
65
66 return 0;
67 }