[英]Does dart support operator overloading
我讀到 Dart 不支持 function 重載。 它是否支持運算符重載? 如果是的話,你能用一個簡單的例子告訴我它是如何完成的嗎? 有哪些優點等?
Dart 支持使用operator關鍵字后跟要重載的運算符的運算符重載。 以下示例重載了MyClass對象的==運算符:
class MyClass {
operator ==(MyClass other) {
// compare this to other
}
}
幾乎所有 Darts 內置運算符都可以重載,但有一些值得注意的例外是賦值運算符=
和引用等價運算符
===
(不再存在)。
至於運算符重載的優勢,它允許您重用具有眾所周知的語義含義的運算符,例如==或+對您的對象進行操作。 例如,如果您有一個重載+運算符的 Matrix 類,那么您可以使用語法m1 + m2而不是更麻煩的m1.plus(m2)來添加兩個矩陣
在新版本中嘗試使用==
運算符重載時,所選答案不再有效。 現在你需要這樣做:
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;
}
您需要使用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;
}
為了擴展 Lars 的答案,您還可以使用內聯函數語法重載運算符。
class MyClass {
operator ==(MyClass o) => id == o.id;
}
學習如何使用運算符重載的一個很好的例子是在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})';
}
}
從 Dart 2.7 版開始,您可以向現有類添加運算符,例如:
extension Contains on String {
bool operator <<(Pattern other) => contains(other);
bool operator >>(String other) => other.contains(this);
}
使用復數作為示例,我可以實現“Complex * num”,例如:
Complex operator *(dynamic b) {
if (b is Complex) {
return Complex( real: ... );
} else if (b is num) {
return Complex.ri(real*b, imaginary*b);
}
}
...
但是如何實現“num * Complex”呢? 有可能嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.