飞镖是否支持运算符重载 [英] Does dart support operator overloading

查看:76
本文介绍了飞镖是否支持运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到Dart不支持函数重载.它是否支持运算符重载.如果是,请在一个简单的示例中告诉我如何完成它.还有什么优势等.我是编程新手. 谢谢.

I read that Dart does not support function overloading. Does it support operator overloading. If yes, would be kind and show me how in a simple example how its done. And what are some advantages etc. I am new to programming. Thanks.

推荐答案

在新版本中尝试重载==运算符时,所选答案不再有效.现在,您需要执行以下操作:

The chosen answer is no longer valid when you try overloads the == operator in new version .Now you need do like this:

class MyClass {
  @override
  bool operator ==(other) {
    // compare this to other
  }
}

但这并不安全.未将other指定为类型,可能会发生意外情况.例如:

But it's not safe.other is not specified as a type, Something unexpected may happened.For example:

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

所以您的云确实是这样的:

So You cloud do like this:

class A {
  A(this.index);

  final int index;

  @override
  bool operator ==(covariant A other) => other.index == index;
}

您需要使用covariant.因为对象会重载==运算符.

You need use covariant.Because Object overloads the == operator.

这篇关于飞镖是否支持运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆