重载指与其它函数具有相同的函数名,但参数不相同的函数实现。
在同一个作用域中,可以为同一个函数名具有多个定义。函数的定义必须在参数列表中的参数类型/数量上彼此不同。
以下示例使用相同的函数 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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)