繁体   English   中英

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

[英]Does dart support operator overloading? (not to be confused with overriding)

这听起来像是完全重复: Does dart support operator overloading
但这个名字具有误导性,问题是关于如何覆盖现有的运算符( ==运算符)。

据我了解,重载 function 意味着具有多个实现,这些实现仅在参数上有所不同,但在 function 的名称上没有变化:

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

相比之下,覆盖意味着重写现有的实现。 由于替换了原来的 function,因此没有名称冲突。 这在 OOP 中很常见,您可以在其中扩展基类 class 并覆盖其方法。

文档说有可重写的运算符。 所以我看到您可以实现自定义运算符。 同时dart不支持重载方法。 那么,dart支持运算符重载吗?

是否可以编写如下代码:

class Matrix{
  Matrix operator+(int b){//...};
  Matrix operator+(Matrix b({//...};
}

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

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);
}

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

有可覆盖的运营商。 所以我看到您可以实现自定义运算符。 同时dart不支持重载方法。 那么,dart支持运算符重载吗?

Dart 语言规范说:

10.1.1 运营商

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

Dart 不支持重载方法(或函数),运算符等同于方法,所以,Dart 不支持运算符重载。

加载 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){

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 个参数定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM