gpt4 book ai didi

function - dart 是否支持运算符重载

转载 作者:行者123 更新时间:2023-12-02 10:55:34 25 4
gpt4 key购买 nike

我读到 Dart 不支持函数重载。它支持运算符重载吗?如果是,您能通过一个简单的示例向我展示它是如何完成的吗?有哪些优点等?

最佳答案

当您在新版本中尝试使用 == 运算符重载时,所选答案不再有效。现在您需要执行以下操作:

class MyClass {
@override
bool operator ==(other) {
// compare this to other
}
}

但这并不安全。 other 未指定为类型,可能会发生意外情况。例如:

void main() {
var a = A(1);
var b = B(1);
var result = a == b;
print(result); //result is true
}

class A {
A(this.index);

final int index;

@override
bool operator ==(other) => other.index == index;
}

class B {
B(this.index);

final int index;
}

所以你可以这样做:

class A {
A(this.index);

final int index;

@override
bool operator ==(covariant A other) => other.index == index;
}

您需要使用协变。因为 Object 重载了 == 运算符。

或者你也可以

测试对象类型:
访问:hash_and_equals

class A {
A(this.index);

final int index;

@override
bool operator ==(other) => other is A && (other.index == index);

@override
int get hashCode => index;
}

关于function - dart 是否支持运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10130472/

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