Dart Language Walkのこのコードスニペットは失敗しますが、このセクションの下オーバーライド演算子のセクションを参照してくださいここに。理由は何ですか?
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);
// use this and the assert will work
// bool operator ==(Vector v) => x == v.x && y == v.y;
// See encubus accepted answer below.
Dump() {
print(this.x);
print(this.y);
}
// Operator == and hashCode not shown. For details, see note below.
// ···
}
final v = Vector(2, 3);
final w = Vector(2, 2);
var x = v+w;
x.dump();
assert(x == Vector(4,5));
assert((v + w) == Vector(4, 5));
すべてのアサートは失敗しますが、x.dump()の出力は4と5です。コードを変更してv + wの周りに()を追加し、+オーバーライドの結果をチェックするようにしました。和。
==
オペレータは、Vectorクラスのために再定義されていません
//演算子==とhashCodeは表示されていません。
それを使用するに==
は、Vector
クラスにを実装する必要があります。
https://api.dart.dev/be/175383/dart-core/Object/operator_equals.html https://api.dart.dev/be/175383/dart-core/Object/hashCode.html
サブクラスが等式演算子をオーバーライドする場合は、一貫性を維持するために、hashCodeメソッドもオーバーライドする必要があります。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加