C++中sizeof类,结果分析

C++中内存分配问题,

在结构体和类中,有很多问题都是求sizeof问题,这个问题不是简单的算出各个类型的长度然后相加就行了,而是要考虑编译器是如何编译这些代码的,是如何为结构体和类中的变量怎么分配内存空间的。http://blog.csdn.net/jimmy54/article/details/5418766,这个地址中讲述了类中的存储情况。下面是我在QT中的代码测试:

#include <QCoreApplication>

#include <iostream>
using namespace std;
class A{
    A();
    ~A();
    void function();
};
//#pragma pack(1)
class B{
private:
    char a;
    int b;
    //double d;
    char c[2];
};
//#pragma pack()
class I{
public:
    virtual void func();
 
};
//#pragma pack(1)
class C:public B{
public:
    //struct B;
    virtual void func();
    char d[9];
   // char d[12];
    double a;
    char b[5];
};//sizeof(C)=4(虚函数地址)+sizeof(B)+d[9]自然对齐+8(double类型)+b[5]最后类成员补齐
//即:4+12+9(12)+8+5(12)=48
//#pragma pack()
class D{
public:
    static int count;
    int a;
    double b;
    char c;
};
class E{
public:
    static int count;
    double b;
    int a;
    char c;
};
class F{
public:
    static int count;
      char c;
      double b;
    int a;
 
};
class H{
public:
 
    char c;
 
    int a;
    double b;
};
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    cout<<" long  is  "<<sizeof(long)<<endl;
    cout<<" int  is  "<<sizeof(int)<<endl;
    cout<<" long long  is  "<<sizeof(long long)<<endl;
    cout<<" double is  "<<sizeof(double)<<endl;
    cout<<" sizof(A) is "<<sizeof(A)<<endl;
    cout<<" sizof(B) is "<<sizeof(B)<<endl;
    cout<<" sizof(I) is "<<sizeof(I)<<endl;
    cout<<" sizof(C) is "<<sizeof(C)<<endl;
    cout<<" sizof(D) is "<<sizeof(D)<<endl;
    cout<<" sizof(E) is "<<sizeof(E)<<endl;
    cout<<" sizof(F) is "<<sizeof(F)<<endl;
    cout<<" sizof(H) is "<<sizeof(H)<<endl;
    return a.exec();
}

 结果:

long is 4

int is 4

long long is 8

double is 8

sizeof(A) is 1

sizeof(B)is 12

sizeof (I)is 4

sizeof (C)is 48

sizeof(D)is 24

sizeof (E)is 16

sizeof (F)is 24

sizeof (H)is 16

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值