C++ 中空類的物件大小是多少?


以下是一個示例程式碼,用於查詢空類的物件大小。

例項

 演示

#include <bits/stdc++.h>
using namespace std;
class p1 {
   public:
   void first() {
      cout << "\nThe parent class p1 function is called.";
   }
};
class p2
{ };
int main() {
   cout << "The size of non-empty class p1 = " << sizeof(p1);
   cout << "\nThe size of empty class p2 = " << sizeof(p2);
   p2 p;
   cout << "\nThe size of object of empty class p2 = " << sizeof(p);
   p1 o;
   cout << "\nThe size of object of non-empty class p1 = " << sizeof(o);
   return 0;
}

輸出

The size of non-empty class p1 = 1
The size of empty class p2 = 1
The size of object of empty class p2 = 1
The size of object of non-empty class p1 = 1

在以上程式中,建立了一個空類 p2。

class p2
{ };

類和物件的大小列印如下 -

cout << "The size of non-empty class p1 : " << sizeof(p1);
cout << "\nThe size of empty class p2 : " << sizeof(p2);
p2 p;
cout << "\nThe size of object of empty class : " << sizeof(p);
p1 o;
cout << "\nThe size of object of non-empty class p1 : " << sizeof(o);

更新時間: 2020-06-26

275 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.