Muh*_*mer 11 overloading function operator-keyword dart
我读到Dart不支持函数重载.它是否支持运算符重载.如果是,那将是善意的,并告诉我如何在一个简单的例子中如何完成它.还有什么优点等我是编程新手.谢谢.
Lar*_*ann 18
是Dart确实支持运算符重载,使用operator关键字,然后是要重载的运算符.以下示例重载MyClass对象的==运算符:
class MyClass {
operator ==(MyClass other) {
// compare this to other
}
}
Run Code Online (Sandbox Code Playgroud)
几乎所有的Darts内置运算符都可以重载一些值得注意的例外,即赋值运算符= 和引用等价运算符===(不再存在).
至于运算符重载的优点,它允许您重用具有众所周知的语义含义的运算符,例如==或+,用于对象的操作.例如,如果您有一个重载+运算符的Matrix类,那么您可以使用语法m1 + m2而不是更麻烦的m1.plus(m2)添加两个矩阵
小智 18
当您==在新版本中尝试使用运算符重载时,所选答案不再有效。现在你需要这样做:
class MyClass {
@override
bool operator ==(other) {
// compare this to other
}
}
Run Code Online (Sandbox Code Playgroud)
但这并不安全。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;
}
Run Code Online (Sandbox Code Playgroud)
所以你可以这样做:
class A {
A(this.index);
final int index;
@override
bool operator ==(covariant A other) => other.index == index;
}
Run Code Online (Sandbox Code Playgroud)
您需要使用covariant. 因为 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;
}
Run Code Online (Sandbox Code Playgroud)
要扩展Lars的答案,您还可以使用内联函数语法重载运算符.
class MyClass {
operator ==(MyClass o) => id == o.id;
}
Run Code Online (Sandbox Code Playgroud)
学习如何使用运算符重载的一个很好的例子是在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) {
// /sf/answers/2880266301/
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})';
}
}
Run Code Online (Sandbox Code Playgroud)