C++类的大小
(i)
如下代码:
#include<iostream>
using namespace std;
class CBase {
};
class CDerive :public CBase {
};
int main(int argc, char* argv[])
{
CDerive p[3];
cout << "sizeof(CBase)=" << sizeof(CBase) << endl
<< "sizeof(CDerive)=" << sizeof(CDerive) << endl;
cout << "sizeof(p)=" << sizeof(p) << endl;
cout << "&p[0]=" << &p[0] << endl
<< "&p[1]=" << &p[1] << endl
<< "&p[2]=" << &p[2] << endl;
return 0;
}
运行结果为:
S:\ComputerTech\VS2015\Release>Test.exe
sizeof(CBase)=1
sizeof(CDerive)=1
sizeof(p)=3
&p[0]=002CF7B8
&p[1]=002CF7B9
&p[2]=002CF7BA
(ii)
将上述代码中的CBase类重新声明如下:
class CBase {
int num;
};
class CDerive :public CBase {
};
再次运行上述程序,结果如下:
S:\ComputerTech\VS2015\Release>Test.exe
sizeof(CBase)=4
sizeof(CDerive)=4
sizeof(p)=12
&p[0]=0023FD88
&p[1]=0023FD8C
&p[2]=0023FD90
(iii)
将(i)中的CBase类声明如下:
class CBase {
int num;
double d;
};
class CDerive :public CBase {
};
运行结果:
S:\ComputerTech\VS2015\Release>Test.exe
sizeof(CBase)=16
sizeof(CDerive)=16
sizeof(p)=48
&p[0]=001DFA98
&p[1]=001DFAA8
&p[2]=001DFAB8
(iv)
将(i)中的CBase类和CDerive类声明如下:
class CBase {
int num;
};
class CDerive :public CBase {
int num2;
};
运行结果:
S:\ComputerTech\VS2015\Release>Test.exe
sizeof(CBase)=4
sizeof(CDerive)=8
sizeof(p)=24
&p[0]=0032F734
&p[1]=0032F73C
&p[2]=0032F744
(v)
将(i)中的CBase类和CDerive类声明如下:
class CBase {
int num;
};
class CDerive :public CBase {
double d;
};
运行结果:
S:\ComputerTech\VS2015\Release>Test.exe
sizeof(CBase)=4
sizeof(CDerive)=16
sizeof(p)=48
&p[0]=0041FE38
&p[1]=0041FE48
&p[2]=0041FE58