dart语言入门:12、运算符重载

Dart语言可以重载以下运算符:

1
2
< 、 + 、 | 、 [] 、 > 、 / 、 ^ 、 []= 、 <= 、 ~/ 、 & 、 ~ 、
>= 、 * 、 << 、 == 、 – 、 % 、 >>

重载 + 和 - 运算符:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Vector {
final int x, y;

Vector(this.x, this.y);

Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
Vector operator -(Vector v) => Vector(x - v.x, y - v.y);
}

void main() {
final v = Vector(2, 3);
final w = Vector(2, 2);

assert(v + w == Vector(4, 5));
assert(v - w == Vector(0, 1));
}

如果重载==,需要实现Object的hashCode的getter。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Person {
final String firstName, lastName;

Person(this.firstName, this.lastName);

@override
int get hashCode {
int result = 17;
result = 37 * result + firstName.hashCode;
result = 37 * result + lastName.hashCode;
return result;
}

@override
bool operator ==(dynamic other) {
if (other is! Person) return false;
Person person = other;
return (person.firstName == firstName &&
person.lastName == lastName);
}
}

void main() {
var p1 = Person('Bob', 'Smith');
var p2 = Person('Bob', 'Smith');
var p3 = 'not a person';
assert(p1.hashCode == p2.hashCode);
assert(p1 == p2);
assert(p1 != p3);
}