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(); |
// 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"); |
} |
Printing int: 5 Printing float: 500.263 Printing string: Hello D运算符重载
可以重新定义或超载最多可用在D内置运算符因此程序员可以使用运算符与用户定义的类型也是如此。
运算符可以使用字符串运算其次是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; |
} |
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); |
} |
Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400
基本上,有三种类型的操作符如下面列出重载。
S.N. | 重载类型 |
---|---|
1 | 一元运算符重载 |
2 | 二元运算符重载 |
3 | 比较操作符重载 |