Dart语言【007】运算符重载

Dart提供了运算符重载,这为代码的书写提供了便利。

例如,int类重载了&、|等运算符,这样我们才能方便地进行位与、位或操作。

// int类的部分代码
abstract class int extends num {
  int operator &(int other);
  int operator |(int other);
  int operator ^(int other);
  int operator ~();
  int operator <<(int shiftAmount);
  int operator >>(int shiftAmount);
}

运算符重载,实际上就是一个成员函数,只不过这个成员函数的名字是“operator运算符”,比如operator+。


下面的代码中,Vector类表示(2维)向量,它重载了+。

class Vector {
  num x;
  num y;
  Vector(this.x, this.y);
  void Print() {
    print("x = ${this.x}, y = ${this.y}");
  }

  Vector operator +(Vector other) {
    Vector v = new Vector(this.x, this.y);
    v.x += other.x;
    v.y += other.y;
    return v;
  }
}

转载于:https://my.oschina.net/jthmath/blog/422421

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值