D編程 Pointer to D classes

2021-09-01 11:30 更新

指向D語言類指針的方式與指向結(jié)構(gòu)指針以及訪問類指針的成員的方式完全相同,您可以使用成員訪問運算符->運算符,就如同對結(jié)構(gòu)的指針一樣。同樣,與所有指針一樣,您必須在使用指針之前對其進行初始化。

讓我們嘗試以下示例,以了解指向類的指針的概念-

import std.stdio;

class Box { 
   public: 
      //Constructor definition 
      this(double l=2.0, double b=2.0, double h=2.0) { 
         writeln("Constructor called."); 
         length=l; 
         breadth=b; 
         height=h; 
      }

      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 
   Box *ptrBox;                //Declare pointer to a class.
   
   //Save the address of first object 
   ptrBox=&Box1; 
   
   //Now try to access a member using member access operator 
   writeln("Volume of Box1: ",ptrBox.Volume()); 
   
   //Save the address of first object 
   ptrBox=&Box2;  
   
   //Now try to access a member using member access operator 
   writeln("Volume of Box2: ", ptrBox.Volume()); 
} 

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

Constructor called. 
Constructor called. 
Volume of Box1: 5.94 
Volume of Box2: 102


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號