C++ 類中的靜態成員



類的靜態成員

我們可以使用static關鍵字定義類的靜態成員。當我們將類的成員宣告為靜態時,這意味著無論建立了多少個類的物件,靜態成員都只有一份複製。

靜態成員由類的所有物件共享。如果不存在其他初始化,則所有靜態資料在建立第一個物件時初始化為零。我們不能將它放在類定義中,但可以在類外初始化它,如下例所示,透過重新宣告靜態變數,使用作用域解析運算子::來標識它屬於哪個類。

示例

讓我們嘗試以下示例來理解靜態資料成員的概念:

#include <iostream>
 
using namespace std;

class Box {
   public:
      static int objectCount;
      
      // Constructor definition
      Box(double l = 2.0, double b = 2.0, double h = 2.0) {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         
         // Increase every time object is created
         objectCount++;
      }
      double Volume() {
         return length * breadth * height;
      }
      
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

// Initialize static member of class Box
int Box::objectCount = 0;

int main(void) {
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects.
   cout << "Total objects: " << Box::objectCount << endl;

   return 0;
}

編譯並執行上述程式碼後,將產生以下結果:

Constructor called.
Constructor called.
Total objects: 2

靜態函式成員

透過將函式成員宣告為靜態,使其獨立於類的任何特定物件。即使不存在類的任何物件,也可以呼叫靜態成員函式,並且static函式僅使用類名和作用域解析運算子::訪問。

靜態成員函式只能訪問靜態資料成員、其他靜態成員函式以及類外部的任何其他函式。

靜態成員函式具有類作用域,它們無法訪問類的this指標。可以使用靜態成員函式來確定是否已建立類的某些物件。

示例

讓我們嘗試以下示例來理解靜態函式成員的概念:

#include <iostream>
 
using namespace std;

class Box {
   public:
      static int objectCount;
      
      // Constructor definition
      Box(double l = 2.0, double b = 2.0, double h = 2.0) {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;

         // Increase every time object is created
         objectCount++;
      }
      double Volume() {
         return length * breadth * height;
      }
      static int getCount() {
         return objectCount;
      }
      
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

// Initialize static member of class Box
int Box::objectCount = 0;

int main(void) {
   // Print total number of objects before creating object.
   cout << "Inital Stage Count: " << Box::getCount() << endl;

   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects after creating object.
   cout << "Final Stage Count: " << Box::getCount() << endl;

   return 0;
}

編譯並執行上述程式碼後,將產生以下結果:

Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2

靜態成員的用例

以下是幾個用例:

  • 單例模式是一種設計模式,它確保類只有一個例項,並提供對其的全域性訪問點。這裡的靜態成員非常適合實現這種模式,因為它們允許維護類的單個共享例項。
  • 靜態成員通常用於管理跨類的所有例項共享的共享資源或計數器。
  • 靜態成員可用於儲存全域性配置設定或常量,這對於管理資源池(例如快取、資料庫連線池等)和實現跨例項共享的日誌系統非常有用。
  • 靜態成員可用於跟蹤方法呼叫。
廣告