Dart提供了运算符重载,这为代码的书写提供了便利。
例如,int类重载了&、|等运算符,这样我们才能方便地进行位与、位或操作。
// int类的部分代码
abstract class int extends num {
int operator &(int other);
int operator |(int other);
int operator ^(int other);
int operator ~();
int operator <<(int shiftAmount);
int operator >>(int shiftAmount);
}
运算符重载,实际上就是一个成员函数,只不过这个成员函数的名字是“operator运算符”,比如operator+。
下面的代码中,Vector类表示(2维)向量,它重载了+。
class Vector {
num x;
num y;
Vector(this.x, this.y);
void Print() {
print("x = ${this.x}, y = ${this.y}");
}
Vector operator +(Vector other) {
Vector v = new Vector(this.x, this.y);
v.x += other.x;
v.y += other.y;
return v;
}
}