D編程 Static members of a class

2021-09-01 11:31 更新

讓我們嘗試以下示例以了解靜態(tài)數(shù)據(jù)成員的概念-

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);  
}

編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-

Constructor called. 
Constructor called. 
Total objects: 2

靜態(tài)函數(shù)

靜態(tài)成員函數(shù)只能從類外部訪問,讓我們嘗試以下示例以了解靜態(tài)函數(shù)成員的概念-

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()); 
} 

編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-

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


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號