1. 什么是运算符重载
- 运算符重载(英语:operator overloading)是多态的一种;
- 运算符重载通常只是一种语法糖,这种语法对语言的功能没有影响,但是更方便程序员使用。让程序更加简洁,有更高的可读性
2. 使用场景
- 当比较两个对象的大小时
- 假设此时有两个商品, 需要比较大小, 规则是按照价格进行比较;当不使用操作符重载时, 写出的代码可能是这样:
if(good1.price < p2.price) {
}
- 有了操作符重载之后:
bool operator <(Good g) {
if (this.price < g.price) {
return true;
}
return false;
}
bool operator >(Good g) => this.price > g.price;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Good &&
runtimeType == other.runtimeType &&
_price == other._price &&
_name == other._name &&
_category == other._category;
@override
int get hashCode => _price.hashCode ^ _name.hashCode ^ _category.hashCode;
- 以后直接使用
good1 < good2
这样的表达式就可以了!
3. 使用操作符重载的注意事项
- operator关键字必须写上,运算符后面的括号中代表的是传入的参数类型和形参;
- 方法体中,return也是必要的,后面跟着需要返回的对象或类型;
- 操作符重载本质是一种函数调用,只不过是一种加了operator关键字的函数,后面的运算符也就是我们需要被重载的运算符,在函数调用的过程中使用运算符调用了相关函数;
- 这样做的好处就是我们可以做一些传统意义上运算符做不了的操作
4. dart中可以重载的操作符集合:
< | + | | | [] |
> | / | ^ | []= |
<= | ~/ | & | ~ |
>= | * | << | == |
– | % | >> | |