上代码:
// test_max.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
void fun1(){};
void fun2(){};
};
class B
{
public:
void fun1(int i=10){};
void fun2(){};
public:
char c;
int a;
};
class C
{
public:
void fun1(){};
virtual void fun2(){};
};
class D
{
public:
void fun1(){};
virtual void fun2(){};
virtual void fun3(){};
public:
int a;
};
int main()
{
A a;
A* a1=new A();
cout<<"A's size is "<<sizeof(A)<<"."<<endl;
cout<<"B's size is "<<sizeof(B)<<"."<<endl;
cout<<"C's size is "<<sizeof(C)<<"."<<endl;
cout<<"D's size is "<<sizeof(D)<<"."<<endl;
cout<<"A's object size is "<<sizeof(a)<<"."<<endl;
cout<<"A's object pointer size is "<<sizeof(a1)<<"."<<endl;
system("pause");
return 0;
}
注:VS2010 Win7 32位
总结:
(1)仅仅含有函数成员的类的大小是1(不知为啥,希望大神解释)
(2)含有数据成员的类的大小为数据成员字节对齐后所占空间大小
(3)含有虚函数类,虚函数所占的空间为四字节(一个指向虚函数表的指针,与虚函数的个数无关)
(4)对象与类所占的空间同样
(5)类对象指针的大小为4