gpt4 book ai didi

flutter - Dart语言演练-覆盖问题

转载 作者:行者123 更新时间:2023-12-03 03:19:39 25 4
gpt4 key购买 nike

尽管Dart Language Walk中的此代码段失败了。请参阅here下有关可重写运算符的部分。知道为什么吗?

  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周围添加(),以便在只声明w而没有断言的情况下检查+覆盖的结果。和。

最佳答案

没有为Vector类重新定义==运算符

// Operator == and hashCode not shown.


您需要为 ==类实现 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方法,以保持一致性。

关于flutter - Dart语言演练-覆盖问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64472577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com