D編程 重載

2021-09-01 10:49 更新

重載指與其它函數(shù)具有相同的函數(shù)名,但參數(shù)不相同的函數(shù)實(shí)現(xiàn)。

函數(shù)重載

在同一個作用域中,可以為同一個函數(shù)名具有多個定義。函數(shù)的定義必須在參數(shù)列表中的參數(shù)類型/數(shù)量上彼此不同。

以下示例使用相同的函數(shù) print()打印不同的數(shù)據(jù)類型-

import std.stdio; 
import std.string; 

class printData { 
   public: 
      void print(int i) { 
         writeln("Printing int: ",i); 
      }

      void print(double f) { 
         writeln("Printing float: ",f );
      }

      void print(string s) { 
         writeln("Printing string: ",s); 
      } 
}; 
 
void main() { 
   printData pd=new printData();  
   
   //Call print to print integer 
   pd.print(5);
   
   //Call print to print float 
   pd.print(500.263); 
   
   //Call print to print character 
   pd.print("Hello D"); 
} 

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

Printing int: 5 
Printing float: 500.263 
Printing string: Hello D

運(yùn)算符重載

您可以重新定義或重載D中可用的大多數(shù)內(nèi)置運(yùn)算符。

可以根據(jù)正在重載的運(yùn)算符,使用字符串op緊隨其后的Add,Sub等來重載運(yùn)算符,我們可以使運(yùn)算符+重載以添加兩個框,如下所示。

Box opAdd(Box b) { 
   Box box=new Box(); 
   box.length=this.length + b.length; 
   box.breadth=this.breadth + b.breadth; 
   box.height=this.height + b.height; 
   return box; 
}

對象作為參數(shù)傳遞,其屬性可以使用該對象訪問,可以使用 this 運(yùn)算符訪問調(diào)用該運(yùn)算符的對象 ,如下所述-

import std.stdio;

class Box { 
   public:  
      double getVolume() { 
         return length * breadth * height; 
      }

      void setLength( double len ) { 
         length=len; 
      } 

      void setBreadth( double bre ) { 
         breadth=bre; 
      }

      void setHeight( double hei ) { 
         height=hei; 
      }

      Box opAdd(Box b) { 
         Box box=new Box(); 
         box.length=this.length + b.length; 
         box.breadth=this.breadth + b.breadth; 
         box.height=this.height + b.height; 
         return box; 
      } 

   private: 
      double length;      //Length of a box 
      double breadth;     //Breadth of a box 
      double height;      //Height of a box 
}; 

//Main function for the program 
void main( ) { 
   Box box1=new Box();    //Declare box1 of type Box 
   Box box2=new Box();    //Declare box2 of type Box 
   Box box3=new Box();    //Declare box3 of type Box 
   double volume=0.0;     //Store the volume of a box here
   
   //box 1 specification 
   box1.setLength(6.0); 
   box1.setBreadth(7.0); 
   box1.setHeight(5.0);
   
   //box 2 specification 
   box2.setLength(12.0); 
   box2.setBreadth(13.0); 
   box2.setHeight(10.0); 
   
   //volume of box 1 
   volume=box1.getVolume(); 
   writeln("Volume of Box1 : ", volume);
   
   //volume of box 2 
   volume=box2.getVolume(); 
   writeln("Volume of Box2 : ", volume); 
   
   //Add two object as follows: 
   box3=box1 + box2; 
   
   //volume of box 3 
   volume=box3.getVolume(); 
   writeln("Volume of Box3 : ", volume);  
} 

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

Volume of Box1 : 210 
Volume of Box2 : 1560 
Volume of Box3 : 5400


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號