假设我们在C ++中有一个空类。现在让我们检查其大小是否为0。实际上,该标准不允许大小为0的对象(或类),因为这将使两个不同的对象具有相同的内存位置成为可能。这就是为什么即使一个空类的大小都必须至少为1的原因。众所周知,一个空类的大小也不为零。通常为1个字节。请参见以下示例。
让我们看下面的实现以更好地理解-
#include<iostream>
using namespace std;
class MyClass {
};
int main() {
cout << sizeof(MyClass);
}输出结果
1
它清楚地表明,一个空类的对象将至少占用一个字节,以确保两个不同的对象具有不同的地址。请参见以下示例。
#include<iostream>
using namespace std;
class MyClass {
};
int main() {
MyClass a, b;
if (&a == &b)
cout <<"Same "<< endl;
else
cout <<"Not same "<< endl;
}输出结果
Not same
对于动态分配,出于相同的原因,new关键字也会返回不同的地址。
#include<iostream>
using namespace std;
class MyClass {
};
int main() {
MyClass *a = new MyClass();
MyClass *b = new MyClass();
if (a == b)
cout <<"Same "<< endl;
else
cout <<"Not same "<< endl;
}输出结果
Not same