如何在C++中建立靜態類?


C++中不存在真正的靜態類。最接近的近似值是一個只包含靜態資料成員和靜態方法的類。

類中的靜態資料成員由所有類物件共享,因為無論類有多少物件,它們在記憶體中只有一份複製。類中的靜態方法只能訪問靜態資料成員、其他靜態方法或類外部的任何方法。

下面是一個演示C++中類中靜態資料成員和靜態方法的程式。

示例

#include <iostream>
using namespace std;
class Example {
   public :
   static int a;
   static int func(int b) {
      cout << "Static member function called";
      cout << "\nThe value of b is: " << b;
      return 0;
   }
};
int Example::a=28;
int main() {
   Example obj;
   Example::func(8);
   cout << "\nThe value of the static data member a is: " << obj.a;
   return 0;
}

輸出

上述程式的輸出如下。

Static member function called
The value of b is: 8
The value of the static data member a is: 28

現在讓我們理解上述程式。

在Example類中,a是int型別的靜態資料成員。func()方法是一個靜態方法,它列印“Static member function called”並顯示b的值。顯示此內容的程式碼片段如下。

class Example {
   public :
   static int a;
   static int func(int b) {
      cout << "Static member function called";
      cout << "\nThe value of b is: " << b;
      return 0;
   }
};
int Example::a = 28;

在main()函式中,建立了一個Example類的物件obj。透過使用類名和範圍解析運算子呼叫func()函式。然後顯示a的值。顯示此內容的程式碼片段如下。

int main() {
   Example obj;
   Example::func(8);
   cout << "\nThe value of the static data member a is: " << obj.a;
   return 0;
}

更新於:2023年4月13日

23K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告