美好的一天,我开发了以下代码来检查点的值是否相等,我为总和编写了一个构造函数并收到了一个错误:
void main() {
var p1 = Point(3, 4, 6);
var p2 = Point(3, 5, 7);
var p3 = p1 + p2;
print(p3.toString());
if (p1 == p2) {
print("they are equal");
} else {
print(false);
}
}
class Point {
int x = 0;
int y = 0;
int z = 0;
Point([this.x = 0, this.y = 0, this.z = 0]);
Point operator +(Point p) =>
Point(this.x + p.x, this.y + p.y, this.z + p.z);
@override
bool operator ==(p) {
return this.x == p.x && this.y == p.y && this.z == p.z; //error is here
}
@override
String toString() {
return "x:$x y:$y z:$z";
}
}
错误是:
The getter 'x' isn't defined for the type 'Object'.
The getter 'y' isn't defined for the type 'Object'.
The getter 'z' isn't defined for the type 'Object'.
答案 0 :(得分:4)
事情是等号运算符中的 p 参数是 Object 类型,它没有 x,y,z 属性。为了使它正确,您首先需要检查 p 是否为 Point。如果不是 - 那么等于将是假的。 p 的检查类型将自动提升为 Point 后,它会进一步工作:
@override
bool operator ==(Object p) {
if(p is! Point) {
return false;
}
return this.x == p.x && this.y == p.y && this.z == p.z; //error is here
}