為什麼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
廣告