C++ 中用户定义类的大小

Size of user defined class in c++

本文关键字:定义 用户 C++      更新时间:2023-10-16

有没有计算c++类大小的方法。 当我创建下面类的对象时,对象的大小为 24 字节。

class student
{
student* pointer;
char * c;
student* AnotherPointer;
class SubClass
{
int a,b;  
};
};

现在从学生类中删除子类,我仍然得到学生类对象的大小为 24。 为什么它没有改变??

class student
{
student* pointer;
char * c;
student* AnotherPointer;
};

有没有计算 c++ 类大小的方法。

可以使用sizeof运算符获取类的大小或任何其他类型。例如:

std::cout << sizeof(student);

删除子类

请注意,名为Subclass的类不是"子类"。它是一个嵌套类。

为什么它没有改变??

因为您没有对类的子对象进行任何更改。嵌套类不是子对象。事实上,它根本不是一个对象——它是一种类型。