我读到Dart不支持函数重载。它是否支持运算符重载。如果是,那将是善意的,并告诉我如何在一个简单的例子中如何完成它。还有什么优点等我是编程新手。 谢谢。
答案 0 :(得分:17)
是Dart支持使用运算符关键字后跟运算符重载,后跟要重载的运算符。以下示例重载 MyClass 对象的 == 运算符:
class MyClass {
operator ==(MyClass other) {
// compare this to other
}
}
几乎所有的Darts内置运算符都可以重载一些值得注意的例外,即赋值运算符 = 和引用等价运算符 === (不再存在)。
至于运算符重载的优势,它允许您重用具有众所周知语义含义的运算符,例如 == 或 + ,以便对对象进行操作。例如,如果您有一个重载 + 运算符的Matrix类,那么您可以使用语法 m1 + m2 添加两个矩阵,而不是使用更加繁琐的 m1.plus (M2)强>
答案 1 :(得分:6)
要扩展Lars的答案,您还可以使用内联函数语法重载运算符。
class MyClass {
operator ==(MyClass o) => id == o.id;
}
答案 2 :(得分:2)
当尝试在新版本中重载==运算符时,所选答案不再有效。现在,您需要执行以下操作:
if (Login::isLoggedIn()) {
echo "
$('.btn1').click(function(){
$.ajax({
type: 'POST',
url: 'api/follow?id={$userid}&artid={$id}',
processData: false,
contentType: 'json/application',
data: '',
success: function(r){
console.log(r)
('#followdiv').html("'+r.follow+'")//error
},
error: function(r){
}
});
});
";
}
但这并不安全。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;
}
。因为对象重载==运算符。
答案 3 :(得分:1)
一个学习如何使用运算符重载的惊人示例是一个在 dart 中处理复数的类:
import 'dart:core';
class Complex {
final double real;
final double imaginary;
Complex({this.real = 0, this.imaginary = 0});
Complex.ri(this.real, this.imaginary);
Complex operator +(Complex b) {
return Complex(
real: this.real + b.real, imaginary: this.imaginary + b.imaginary);
}
Complex operator -(Complex b) {
return Complex(
real: this.real - b.real, imaginary: this.imaginary - b.imaginary);
}
Complex operator *(Complex b) {
return Complex(
real: this.real * b.real - this.imaginary * b.imaginary,
imaginary: this.real * b.imaginary + this.imaginary * b.real);
}
Complex operator /(Complex b) {
// https://stackoverflow.com/a/41146661/6846888
var conjugation = b.conjugate();
var denominatorRes = b * conjugation;
// denominator has only real part
var denominator = denominatorRes.real;
var nominator = this * conjugation;
return Complex(
real: nominator.real / denominator,
imaginary: nominator.imaginary / denominator);
}
bool operator ==(b) {
return b.real == this.real && b.imaginary == this.imaginary;
}
@override
String toString() {
return 'Complex(real: ${real}, imaginary: ${imaginary})';
}
}
答案 4 :(得分:0)
从 Dart 2.7 版开始,您可以向现有类添加运算符,例如:
extension Contains on String {
bool operator <<(Pattern other) => contains(other);
bool operator >>(String other) => other.contains(this);
}