为什么C++中空类的尺寸不为零?
假设我们在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关键字也会返回不同的地址。
示例 (C++)
#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
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP