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