D 语言 - 比较运算符重载
下表显示了比较运算符及其用途的列表。
| 函数名称 | 运算符 | 用途 |
|---|---|---|
| opCmp | < | 是否之前 |
| opCmp | <= | 是否之后 |
| opCmp | > | 是否之后 |
| opCmp | >= | 是否之前 |
比较运算符用于对数组进行排序。 以下示例展示了如何使用比较运算符。
import std.random;
import std.stdio;
import std.string;
struct Box {
int volume;
int opCmp(const ref Box box) const {
return (volume == box.volume ? box.volume - volume: volume - box.volume);
}
string toString() const {
return format("Volume:%s\n", volume);
}
}
void main() {
Box[] boxes;
int j = 10;
foreach (i; 0 .. 10) {
boxes ~= Box(j*j*j);
j = j-1;
}
writeln("Unsorted Array");
writeln(boxes);
boxes.sort;
writeln("Sorted Array");
writeln(boxes);
writeln(boxes[0]<boxes[1]);
writeln(boxes[0]>boxes[1]);
writeln(boxes[0]<=boxes[1]);
writeln(boxes[0]>=boxes[1]);
}
当上面的代码被编译并执行时,会产生以下结果 −
Unsorted Array [Volume:1000 , Volume:729 , Volume:512 , Volume:343 , Volume:216 , Volume:125 , Volume:64 , Volume:27 , Volume:8 , Volume:1 ] Sorted Array [Volume:1 , Volume:8 , Volume:27 , Volume:64 , Volume:125 , Volume:216 , Volume:343 , Volume:512 , Volume:729 , Volume:1000 ] true false true false
❮ d_programming_overloading.html

