介绍
如果你之前做过C++开发,你肯定会了解操作符的重载,如果你只是做Java,可能会忽略这一点
什么是操作符重载
操作符重载允许你为自定义类定义操作符的行为。这样,你可以使用标准的操作符(如 +
、-
、*
等)来操作自定义类的对象,从而提高代码的可读性和易用性。简单说之前 +
、-
、*
等只是应在算数计算中,现在你可以自定义在对象上。
如何重载操作符
要重载一个操作符,你需要在自定义类中实现一个特殊的方法,该方法的名称由 operator
关键字和要重载的操作符组成。
官方示例
在UI布局的时候,需要确定绘制的区域。就需要知道它在父控件的位置,以及它自身的大小。下面我们看Flutter中Offset
的处理:比如&
的重载
Rect operator &(Size other) => Rect.fromLTWH(dx, dy, other.width, other.height);
传入的是Size,那么根据Offset和Size就可以确定具体的位置,所以返回的是Rect。这在渲染的时候使用非常的方便。
Offset其他重载运算
class Offset extends OffsetBase {
/// Creates an offset. The first argument sets [dx], the horizontal component,
/// and the second sets [dy], the vertical component.
const Offset(double dx, double dy) : super(dx, dy);
Offset operator -() => Offset(-dx, -dy);
Offset operator -(Offset other) => Offset(dx - other.dx, dy - other.dy);
Offset operator +(Offset other) => Offset(dx + other.dx, dy + other.dy);
Offset operator *(double operand) => Offset(dx * operand, dy * operand);
Offset operator /(double operand) => Offset(dx / operand, dy / operand);
Offset operator ~/(double operand) => Offset((dx ~/ operand).toDouble(), (dy ~/ operand).toDouble());
Offset operator %(double operand) => Offset(dx % operand, dy % operand);
Rect operator &(Size other) => Rect.fromLTWH(dx, dy, other.width, other.height);
@override
bool operator ==(Object other) {
return other is Offset
&& other.dx == dx
&& other.dy == dy;
}
}