在C语言中引入该结构时,没有 物体 当时。因此,根据C标准,决定将空结构的大小保持为零。
在C++中,空结构/类的大小为 一字节 至于调用函数,至少空的结构/类应该有一定的大小( 最小1字节 是必需的),即一个字节使其可区分。
现在,为了了解空类的大小,让我们先了解什么是空类!
空类: 它是一个不包含任何数据成员(例如int a、float b、char c和string d等)的类。然而,空类可能包含成员函数。
为什么C++中的空类占用一个字节?
简单地说,没有对象的类不需要为其分配空间。在实例化类时会分配空间,因此编译器会将1个字节分配给空类的对象,以标识其唯一的地址。
如果一个类有多个对象,它们可以有不同的唯一内存位置。假设,如果一个类没有任何大小,内存位置上会存储什么?这是我们在C++程序中创建空类对象的原因,它需要一些内存来存储,并且可以保留的最小内存量是1字节。因此,如果我们创建一个空类的多个对象,每个对象都将有一个唯一的地址。
下面的代码显示了空类的大小:
CPP
// C++ program without any compilation // error to demonstrate the size of // an Empty Class #include <iostream> using namespace std; // Creating an Empty Class class Empty_class { }; // Driver Code int main() { cout << "Size of Empty Class is = " << sizeof (Empty_class); return 0; } |
Size of Empty Class is = 1
空类的大小不是零。通常为1字节。它是非零的,以确保两个不同的对象将具有不同的地址。请参见下面的示例。
CPP
// C++ program without any compilation // error to demonstrate that the size // of the two different objects of an // Empty Class will have different // addresses #include <iostream> using namespace std; // Creating an Empty class class Empty { }; // Driver Code int main() { Empty a, b; if (&a == &b) cout << "Impossible " << endl; else cout << "Fine " << endl; return 0; } |
Fine
出于同样的原因(不同的对象应该有不同的地址), “新的” 始终返回指向不同对象的指针。请参见下面的示例。
C++
// C++ program without any // compilation error to demonstrate // that "new" always returns pointers // to distinct objects #include <iostream> using namespace std; // Creating an Empty Class class Empty { }; // Driver Code int main() { Empty* p1 = new Empty; Empty* p2 = new Empty; if (p1 == p2) cout << "Impossible " << endl; else cout << "Fine " << endl; return 0; } |
Fine
现在,猜猜下面程序的输出:
CPP
// CPP Program as an exercise #include <iostream> using namespace std; // Creating an Empty Class class Empty { }; // Creating a Derived Class class Derived : Empty { int a; }; // Driver Code int main() { cout << sizeof (Derived); return 0; } |
4
注: 输出不大于4。有一条有趣的规则说,空基类不需要用单独的字节来表示。因此,编译器可以在基类为空的情况下自由地进行优化。
作为练习,在编译器上尝试以下程序。
CPP
// CPP Program as an exercise #include <iostream> using namespace std; class Empty { }; class Derived1 : public Empty { }; class Derived2 : virtual public Empty { }; class Derived3 : public Empty { char c; }; class Derived4 : virtual public Empty { char c; }; class Dummy { char c; }; int main() { cout << "sizeof(Empty) " << sizeof (Empty) << endl; cout << "sizeof(Derived1) " << sizeof (Derived1) << endl; cout << "sizeof(Derived2) " << sizeof (Derived2) << endl; cout << "sizeof(Derived3) " << sizeof (Derived3) << endl; cout << "sizeof(Derived4) " << sizeof (Derived4) << endl; cout << "sizeof(Dummy) " << sizeof (Dummy) << endl; return 0; } |
sizeof(Empty) 1sizeof(Derived1) 1sizeof(Derived2) 8sizeof(Derived3) 1sizeof(Derived4) 16sizeof(Dummy) 1
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。