在这里列出了空类,类有函数,值,没有函数的大小,注意Class是默认字节对齐
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string> using namespace std; #include <stdio.h> class x { }; class cx { public: cx() { } ~cx() { } }; class cxHasVirtual { public: cxHasVirtual() { } virtual ~cxHasVirtual() { } }; class cxHasVirFunc { public: cxHasVirFunc() { } virtual ~cxHasVirFunc() { } virtual int setA() { int a = 5; } }; class cxHasVal { public: cxHasVal() { } ~cxHasVal() { } int a; char y; }; class cxHasValFunc { public: cxHasValFunc() { } ~cxHasValFunc() { } int a; char y; int getASize() { return sizeof(a); } void setA() { a = 5; } }; int main() { x emptyX; int emptySize = sizeof(x); printf("size of empty class is %d ", emptySize); cx *classx = new cx(); int clsizePt = sizeof(classx); int clsize = sizeof(cx); printf("size of class point is %d ", clsizePt); printf("size of class is %d ", clsize); cxHasVirtual *classVirtual = new cxHasVirtual(); int clsizeVirtualPt = sizeof(classVirtual); int clsizeVirtual = sizeof(cxHasVirtual); int clsizeVirFunc = sizeof(cxHasVirFunc); printf("size of class point has virtual is %d ", clsizeVirtualPt); printf("size of class has virtual is %d ", clsizeVirtual); printf("size of class has virtual destruct and fun is %d ", clsizeVirFunc); cxHasVal *hasVal = new cxHasVal(); hasVal->a = 12; int hasValSize = sizeof(hasVal); int rVal = sizeof(cxHasVal); printf("size of class Point has val is %d ", hasValSize); printf("size of class has val is %d ", rVal); cxHasValFunc *hasValFunc = new cxHasValFunc(); int hasValFuncSize = sizeof(hasValFunc); int rValFunc = sizeof(cxHasValFunc); printf("size of class Point has val is %d ", hasValFuncSize); printf("size of class has val Func is %d ", rValFunc); return 0; }
运行结果:
结论:1.空类的大小和含有构造和析构函数的类的大小为1个字节;
2.New的class的大小为指针所占用的内存,为4,与类的大小以及是否含有变量和函数无关;
3. 含有虚函数的类,由于虚函数需要建立一张虚函数表,指针指向虚函数表,而指针的大小为4,所以含有虚函数的类大小增加4个字节;
4. 含有函数和变量的类的大小为变量的大小的集合,这里变量为int和char, 由于字节对齐,大小为8;
5.类的大小与函数无关