首先,看一个题目:以下代码使用VC编译成32位可执行程序,请问:nLenA、nLenAObject、nLenB、nLenAObject、nLenC、nLenCObject的值分别为
#include<iostream>
#include<stdlib.h>
using namespace std;
class t_classA
{
public:
t_classA(){};
~t_classA(){};
};
class t_classB
{
public:
t_classB(){};
virtual ~t_classB(){};
};
class t_classC:public t_classA,public t_classB
{
public:
t_classC(){};
virtual ~t_classC(){};
};
int main()
{
int nLenA = sizeof(t_classA);
cout<<"nLenA: "<<nLenA<<endl;
t_classA oA;
int nLenAObject = sizeof(oA);
cout<<"nLenAObject: "<<nLenAObject<<endl;
int nLenB = sizeof(t_classB);
cout<<"nLenB: "<<nLenB<<endl;
t_classB oB;
int nLenBObject = sizeof(oB);
cout<<"nLenBObject: "<<nLenBObject<<endl;
int nLenC = sizeof(t_classC);
cout<<"nLenC: "<<nLenC<<endl;
t_classC oC;
int nLenCObject = sizeof(oC);
cout<<"nLenCObject: "<<nLenCObject<<endl;
}
下面进行全面的分析:
1、空类
#include<iostream>
#include<stdlib.h>
using namespace std;
class A//1
{
};
int main()
{
A a;
cout<<sizeof(A)<<endl;//1
cout<<sizeof(a)<<endl;//1
}
2、一般非空
#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
int a;//4
int *p;//4
char c;//1
};
int main()
{
A a;
cout<<sizeof(A)<<endl;//12
cout<<sizeof(a)<<endl;//12
}
3.有虚函数
#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
public:
A(){};
virtual ~A(){};//4
private:
int b;//4
int *p;//4
char c;//1
};
int main()
{
A a;
cout<<sizeof(A)<<endl;//16
cout<<sizeof(a)<<endl;//16
}
4.虚函数继承
#include<iostream>
#include<stdlib.h>
using namespace std;
class A//16
{
public:
A(){};
virtual ~A(){};
private:
int b;
int *p;
char c;
};
class B:public A
{
public:
B(){};
~B(){};
private:
int b;//4
};
int main()
{
B b;
cout<<sizeof(B)<<endl;//20
cout<<sizeof(b)<<endl;//20
}
5.静态成员函数
#include<iostream>
#include<stdlib.h>
using namespace std;
class A//1
{
static int n;//0
};
int main()
{
A a;
cout<<sizeof(A)<<endl;//1
cout<<sizeof(a)<<endl;//1
}
#include<iostream>
#include<stdlib.h>
using namespace std;
class A//1
{
func();//0
};
int main()
{
A a;
cout<<sizeof(A)<<endl;//1
cout<<sizeof(a)<<endl;//1
}
所以结果如下:
nLenA=1
nLenAObject=1
nLenB=4
nLenAObject=4
nLenC=4
nLenCObject=4
参考:http://blog.csdn.net/zzhongcy/article/details/38361755