D语言 - 重载

D语言 - 重载 首页 / D语言入门教程 / D语言 - 重载

重载指与其它函数具有相同的函数名,但参数不相同的函数实现。

函数重载

在同一个作用域中,可以为同一个函数名具有多个定义。函数的定义必须在参数列表中的参数类型/数量上彼此不同。

以下示例使用相同的函数 print()打印不同的数据类型-

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();  
   
   //调用 print 打印整数
   pd.print(5);
   
   //调用 print 打印浮点数
   pd.print(500.263); 
   
   //调用print打印字符
   pd.print("Hello Learnfk"); 
} 

编译并执行上述代码后,将产生以下输出-

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

运算符重载

您可以重新定义或重载D中可用的大多数内置运算符。

可以根据正在重载的运算符,使用字符串op紧随其后的Add,Sub等来重载运算符,我们可以使运算符+重载以添加两个框,如下所示。

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

对象作为参数传递,其属性可以使用该对象访问,可以使用 this 运算符访问调用该运算符的对象 ,如下所述-

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;      //长 
      double breadth;     //宽
      double height;      //高
}; 

//主函数
void main( ) { 
   Box box1=new Box();    //实例化box1
   Box box2=new Box();    
   Box box3=new Box();    
   double volume=0.0;     //存储体积变量
   
   //box1赋值
   box1.setLength(6.0); 
   box1.setBreadth(7.0); 
   box1.setHeight(5.0);
   
   //box2赋值
   box2.setLength(12.0); 
   box2.setBreadth(13.0); 
   box2.setHeight(10.0); 
   
   //box1体积
   volume=box1.getVolume(); 
   writeln("Volume of Box1 : ", volume);
   
   //box2体积
   volume=box2.getVolume(); 
   writeln("Volume of Box2 : ", volume); 
   
   //添加两个对象如下:
   box3=box1 + box2; 
   
   //volume of box 3 
   volume=box3.getVolume(); 
   writeln("Volume of Box3 : ", volume);  
} 

编译并执行上述代码后,将产生以下输出-

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

硅谷产品实战36讲 -〔曲晓音〕

重学前端 -〔程劭非(winter)〕

安全攻防技能30讲 -〔何为舟〕

NLP实战高手课 -〔王然〕

后端存储实战课 -〔李玥〕

重学线性代数 -〔朱维刚〕

技术面试官识人手册 -〔熊燚(四火)〕

技术领导力实战笔记 2022 -〔TGO 鲲鹏会〕

AI大模型企业应用实战 -〔蔡超〕

好记忆不如烂笔头。留下您的足迹吧 :)