先看一下c++结构体
struct Son {
int age;
int money;
void run() {
cout << "Person::runm()" << age << endl;
}
};
int main() {
Son son;
cout << sizeof(son) << endl;
getchar();
return 0;
}
//很显然,由于run这些方法,都放在方法区,并不占结构体内存,因此输出结果是8
exe:8
如果结构体里面数据类型不一致呢?
struct Son {
int age;
char sex;
void run() {
cout << "Person::runm()" << age << endl;
}
};
int main() {
Son son;
cout << sizeof(son) << endl;
getchar();
return 0;
}
//这个时候因为int占4字节,char占1字节,总共5字节,但是最大字节数为4,5不能被4整除,因此需要补齐,最终为8字节
exe:8
在增加一点呢?
struct Son {
int age;
char sex;
short aaa;
void run() {
cout << "Person::runm()" << age << endl;
}
};
int main() {
Son son;
cout << sizeof(son) << endl;
getchar();
return 0;
}
//int-4 char-1 short-2 因此,如果int开始的地方是0x0000 则char开始的地址0x0004,但是short占两个字节,char占一个字节,不能被2整除,因此需要补一个字节,因此short开始的位置是0x0006,结束地址是0x0007,总共8字节
总结:
前面的地址必须是后面的地址正数倍,不是就补齐
整个Struct的地址必须是最大字节的整数倍
个人理解,不对欢迎指正
原文:https://www.cnblogs.com/antake/p/13358705.html