D 程式設計 - 類的靜態成員



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

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

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

import std.stdio;

class Box { 
   public: 
      static int objectCount = 0;

      // Constructor definition 
      this(double l = 2.0, double b = 2.0, double h = 2.0) { 
         writeln("Constructor called."); 
         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 
};
  
void main() { 
   Box Box1 = new Box(3.3, 1.2, 1.5);    // Declare box1 
   Box Box2 = new Box(8.5, 6.0, 2.0);    // Declare box2  
   
   // Print total number of objects. 
   writeln("Total objects: ",Box.objectCount);  
}

當編譯並執行上述程式碼時,會產生以下結果:

Constructor called. 
Constructor called. 
Total objects: 2

靜態函式成員

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

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

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

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

import std.stdio;

class Box { 
   public: 
      static int objectCount = 0; 
      
      // Constructor definition 
      this(double l = 2.0, double b = 2.0, double h = 2.0) { 
         writeln("Constructor called."); 
         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 
};
  
void main() { 
   // Print total number of objects before creating object. 
   writeln("Inital Stage Count: ",Box.getCount());  
   
   Box Box1 = new Box(3.3, 1.2, 1.5);    // Declare box1 
   Box Box2 = new Box(8.5, 6.0, 2.0);    // Declare box2 
   
   // Print total number of objects after creating object. 
   writeln("Final Stage Count: ",Box.getCount()); 
} 

當編譯並執行上述程式碼時,會產生以下結果:

Inital Stage Count: 0 
Constructor called. 
Constructor called
Final Stage Count: 2 
d_programming_classes_objects.htm
廣告

© . All rights reserved.