D编程允许为一个函数名或在相同的范围内操作,这就是所谓的函数重载和运算符重载分别指定一个以上的定义。
重载声明的是,已被声明具有相同的名称,在同一范围内先前声明的声明的声明,除了这两个声明具有不同的参数和明显不同的定义(实现)。
当调用一个重载函数或运算符,编译器确定最合适的定义,通过比较你用来调用函数或运算符的定义中指定的参数类型的参数类型来使用。选择最合适的重载函数或运算符的过程被称为重载解析。
函数重载
可以有相同的函数名多个定义在相同的范围。该函数的定义必须由类型和/或参数在参数列表中的号码彼此不同。不能重载函数声明只相差返回类型。
以下是其中相同功能的print()被用于打印不同的数据类型的示例:
importstd.stdio;importstd.string;classprintData{public:voidprint(inti){writeln("Printing int: ",i);}voidprint(doublef){writeln("Printing float: ",f);}voidprint(strings){writeln("Printing string: ",s);}};voidmain(){printData pd=newprintData();// Call print to print integerpd.print(5);// Call print to print floatpd.print(500.263);// Call print to print characterpd.print("Hello D");}
让我们编译和运行上面的程序,这将产生以下结果:
Printing int: 5
Printing float: 500.263
Printing string: Hello D
运算符重载
可以重新定义或超载最多可用在D内置运算符因此程序员可以使用运算符与用户定义的类型也是如此。
运算符可以使用字符串运算其次是ADD,SUB超载等基于正被重载的运算符。我们可以重载运算符+,如下图所示添加两个箱子。
BoxopAdd(Boxb){Boxbox=newBox();box.length=this.length+b.length;box.breadth=this.breadth+b.breadth;box.height=this.height+b.height;returnbox;}
以下是该示例使用一个成员函数来显示运算符的重载的概念。在这里,一个对象作为参数传递,其属性将使用此对象来访问,这将调用this操作符的对象可以使用此运算符来访问,解释如下:
importstd.stdio;classBox{public:doublegetVolume(){returnlength*breadth*height;}voidsetLength(doublelen){length=len;}voidsetBreadth(doublebre){breadth=bre;}voidsetHeight(doublehei){height=hei;}BoxopAdd(Boxb){Boxbox=newBox();box.length=this.length+b.length;box.breadth=this.breadth+b.breadth;box.height=this.height+b.height;returnbox;}private:doublelength;// Length of a boxdoublebreadth;// Breadth of a boxdoubleheight;// Height of a box};// Main function for the programvoidmain(){Boxbox1=newBox();// Declare box1 of type BoxBoxbox2=newBox();// Declare box2 of type BoxBoxbox3=newBox();// Declare box3 of type Boxdoublevolume=0.0;// Store the volume of a box here// box 1 specificationbox1.setLength(6.0);box1.setBreadth(7.0);box1.setHeight(5.0);// box 2 specificationbox2.setLength(12.0);box2.setBreadth(13.0);box2.setHeight(10.0);// volume of box 1volume=box1.getVolume();writeln("Volume of Box1 : ",volume);// volume of box 2volume=box2.getVolume();writeln("Volume of Box2 : ",volume);// Add two object as follows:box3=box1+box2;// volume of box 3volume=box3.getVolume();writeln("Volume of Box3 : ",volume);}
当上面的代码被编译并执行,它会产生以下结果:
VolumeofBox1:210VolumeofBox2:1560VolumeofBox3:5400
运算符重载类型:
基本上,有三种类型的操作符如下面列出重载。
¥ 我要打赏
纠错/补充
收藏
加QQ群啦,易百教程官方技术学习群
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。