C++ SIZEOF 关键词

黎 浩然/ 5 5 月, 2022/ C/C++, 计算机/COMPUTER/ 0 comments

空类的实例

/**
* @file blackclass.cpp
* @brief 空类的实例大小为1字节 * @author Ernest
* @version v1
* @date 2019-07-21
*/
#include<iostream>
using namespace std;

class A{};

int main() {
    cout<<sizeof(A)<<endl;
    return 0; 
}
//1

静态数据成员

/**
* @file static.cpp
* @brief 静态数据成员不影响实例的大小 * @author Ernest
* @version v1
* @date 2019-07-21
*/
#include<iostream>
using namespace std;

class A {
public:
    char b;
    virtual void fun() {};
    static int c;
    static int d;
    static int f;
};

int main() {
    /**
     * @brief 16字节对齐、静态变量不影响类的大小、vptr指针=8
     */
    class A *a = new A();
    a->fun();
    a->b = 3;
    cout<<sizeof(*a)<<endl;
    return 0;
}
//16

虚函数表指针在对象内存的开始

然后才是成员变量b

Share this Post

Leave a Comment

您的邮箱地址不会被公开。 必填项已用 * 标注

*
*