飞镖是否支持运算符重载? (不要与覆盖混淆)

问题描述 投票:0回答:4

这听起来像是:Does dart support operator overloading的重复项但是名称令人误解,问题在于如何覆盖现有的运算符(==运算符)。

据我所知,重载一个函数意味着具有多个实现,这些实现仅在其参数上有所不同,而在函数名称上却没有变化:

int max(int a, int b);
double max(double a, double b);

相反,覆盖意味着重写现有的实现。由于原始功能已被替换,因此不会发生名称冲突。这在OOP中很常见,您可以在其中扩展基类并覆盖其方法。

docs表示存在可重写的运算符。因此,我看到您可以实现自定义运算符。同时,dart不支持重载方法。那么,dart是否支持重载运算符?

是否可以编写以下代码:

class Matrix{
  Matrix operator+(int b){//...};
  Matrix operator+(Matrix b({//...};
}
dart
4个回答
3
投票

是的,您绝对可以这样做,但是您需要检查单个方法中的类型,因为一个操作符不能有重复的方法:

class Matrix {
  int num = 0;
  Matrix(this.num);
  Matrix operator+(dynamic b) {
    if(b is int) {
      return Matrix(this.num + b);  
    } else if(b is Matrix){
      return Matrix(this.num + b.num);
    } 
  }
}

void main() {
  print((Matrix(5) + 6).num);  

  print((Matrix(7) + Matrix(3)).num);
}

0
投票

加载dartpad后,dart似乎不支持重载运算符:

class A{
  operator*(int b){
    print("mul int");
  }
  operator*(double b){
    print("mul double");
  }
}

导致错误消息:

Error compiling to JavaScript:
main.dart:5:11:
Error: '*' is already declared in this scope.
  operator*(double b){

0
投票

geometry.dart中有以下几行:

  /// Unary negation operator.
  ///
  /// Returns an offset with the coordinates negated.
  ///
  /// If the [Offset] represents an arrow on a plane, this operator returns the
  /// same arrow but pointing in the reverse direction.
  Offset operator -() => Offset(-dx, -dy);

After some research it appears that `-` operator can be used with 0 or 1 parameter, which allows it to be defined twice.

  /// Binary subtraction operator.
  ///
  /// Returns an offset whose [dx] value is the left-hand-side operand's [dx]
  /// minus the right-hand-side operand's [dx] and whose [dy] value is the
  /// left-hand-side operand's [dy] minus the right-hand-side operand's [dy].
  ///
  /// See also [translate].
  Offset operator -(Offset other) => Offset(dx - other.dx, dy - other.dy);

这仅是由于可以用0或1个参数定义-运算符。


0
投票

您基本上已经回答了自己的问题。

有可重写的运算符。因此,我看到您可以实现自定义运算符。同时,dart不支持重载方法。那么,dart是否支持重载运算符?

Dart语言规范说:

10.1.1运算符

运算符是具有特殊名称的实例方法。

Dart不支持重载方法(或函数),运算符等效于方法,因此,ergo,Dart不支持运算符重载。

© www.soinside.com 2019 - 2024. All rights reserved.