preFly

人要有所担当,
更要有所取舍!
常见数据类型所占空间sizeof

网上很多人都说,内置数据类型所占空间与不同的编译环境甚至编程语言有关,于是我就来看看自己的机器下,他们到底占多大空间吧

直接上代码~

#include "stdafx.h"
#include <iostream>
#include <iomanip>

using namespace std;

class A
{
};
class B
{
    virtual void f(){}
};
class C:public B
{
};
class D:public virtual A
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    //The following part is to test the length of int, short, long, char, float and double
    //Different computer may have different results
    cout<<"int->"<<sizeof(int)<<endl;          //4
    cout<<"short->"<<sizeof(short)<<endl;      //2
    cout<<"long->"<<sizeof(long)<<endl;        //4
    cout<<"char->"<<sizeof(char)<<endl;        //1
    cout<<"float->"<<sizeof(float)<<endl;      //4
    cout<<"double->"<<sizeof(double)<<endl;    //8

    char s[2][3]={"aa","bb"};
    cout<<s[0]<<endl;          //输出aa
    cout<<s[1]<<endl;          //输出bb
    cout<<sizeof s <<endl;     //输出6,由上面的代码可知,每个char是一字节,所以2×3×1=6
    cout<<sizeof &s<<endl;     //输出4,也就是任意指针的大小
    cout<<sizeof s[0]<<endl;   //输出3

    cout<<"sizeof(A):"<<sizeof(A)<<endl;    //输出1,空类所占空间为1
    cout<<"sizeof(B):"<<sizeof(B)<<endl;    //输出4,虚类中包含一个指向虚表的指针
    cout<<"sizeof(C):"<<sizeof(C)<<endl;    //输出4,同上
    cout<<"sizeof(D):"<<sizeof(D)<<endl;    //输出4,同上

    return 0;
}

posted on 2010-10-08 16:44  preFly  阅读(551)  评论(0编辑  收藏  举报