C++之类成员所占内存大小问题总结

1.空类所占字节数为1,可见代码如下

#include <iostream>
using namespace std;

class Parent
{

};

class Child:public Parent
{
public:
    int b ;
};

int main(int argc, char* argv[])
{
    Child b;
    Parent a;

    cout << "a.sizeof = " << sizeof(a) << endl;
    cout << "b.sizeof = " << sizeof(b) << endl;

    system("pause");
    return 0;
}

打印结果为:

  

分析:

  为了能够区分不同的对象,一个空类在内存中只占一个字节;

  在子类继承父类后,如果子类仍然是空类,则子类也在内存中指针一个字节;

           如果子类不是空类,则按照成员变量所占字节大小计算。

 

2.类中的成员函数不占内存空间,虚函数除外;

#include <iostream>
using namespace std;

class Parent
{
public:
    void func() {};
    void func1() { int a; };
    void func2() { int b; };
};

class Child:public Parent
{
public:
    int b ;
};

int main(int argc, char* argv[])
{
    Child b;
    Parent a;

    cout << "a.sizeof = " << sizeof(a) << endl;
    cout << "b.sizeof = " << sizeof(b) << endl;

    system("pause");
    return 0;
}

输出结果如下:

  

分析:上述代码中父类,在内存中仍然只占有一个字节;原因就是因为函数在内存中不占字节;

   但是,如果父类中如果有一个虚函数,则类所字节发生变化,如果是32位编译器,则占内存四个字节;

#include <iostream>
using namespace std;

class Parent
{
public:
    virtual void func() {};
    virtual void func1() { int a; };
    void func2() { int b; };
};

class Child:public Parent
{
public:
    int b ;
};

int main(int argc, char* argv[])
{
    Child b;
    Parent a;

    cout << "a.sizeof = " << sizeof(a) << endl;
    cout << "b.sizeof = " << sizeof(b) << endl;

    system("pause");
    return 0;
}

输出结果:

  

分析:

  通过上述代码可见,编译器为32时,无论几个虚函数所占的字节数都为4;

  而子类在内存中占的字节数为父类所占字节数+自身成员所占的字节数;

 

3.和结构体一样,类中自身带有四字节对齐功能

#include <iostream>
using namespace std;

class Parent
{
public:
    char a;
    virtual void func() {};
    virtual void func1() { int a; };
    void func2() { int b; };
};

class Child:public Parent
{
public:
    char c;
    int b ;
};

int main(int argc, char* argv[])
{
    Child b;
    Parent a;

    cout << "a.sizeof = " << sizeof(a) << endl;
    cout << "b.sizeof = " << sizeof(b) << endl;

    system("pause");
    return 0;
}

输出结果:

  

分析:

  Parent类中,char a;占一个字节,虚函数占有四个字节,由于类的字节对齐,所以总共父类占有8个字节;

  子类中,char c 占有一个字节,int 占四个字节,由于字节对齐,本身共占有8字节,再加上父类的8字节,共占有16字节;

 

4.类中的static静态成员变量不占内存,静态成员变量存储在静态区

#include <iostream>
using namespace std;

class G
{
public:
    static int a;
};

int main(int argc, char * argv[]) 
{
    
    cout << sizeof(G)<<endl;

    system("pause");
    return 0;

}

结果输出:

  

总结:

  1.空类必须占一个字节;

  2.函数指针不占字节;

  3.虚函数根据编译器位数,占相应字节;

  4.类具有4字节对齐功能;

  5.类中的静态成员变量不占类的内存;并且静态成员变量的初始化必须在类外初始化;

 

转载于:https://www.cnblogs.com/weiyouqing/p/9642986.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值