父类的成员变量在前,子类的成员变量在后。
#include <iostream>
using namespace std;
struct Person
{
int m_age;
};
struct Student : Person
{
int m_no;
};
struct GoodStudent : Student
{
int m_money;
};
int main()
{
Person person;
cout << sizeof(person) << endl; // 4
Student stu;
cout << sizeof(stu) << endl; // 8
GoodStudent gs;
cout << sizeof(gs) << endl; // 12
gs.m_money = 666;
gs.m_no = 1;
gs.m_age = 20;
cout << "&gs = " << &gs << endl;
cout << "&gs.m_age = " << &gs.m_age << endl;
cout << "&gs.m_no = " << &gs.m_no << endl;
cout << "&gs.m_money = " << &gs.m_money << endl;
return 0;
}
输出结果如下:
内存布局如下: