6
5
4
3
2
是发发
操作符覆写

操作符覆写

class Person {
int age;
Person(this.age);
bool operator > (Person person) {
return this.age > person.age;
}
int operator [] (String str) {
if (str == "age") {
return this.age;
}
return 0;
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Person &&
runtimeType == other.runtimeType &&
age == other.age;
@override
int get hashCode => age.hashCode;
}
对象操作符覆写
1、覆写操作符需要在类中定义
返回类型 operator 操作符 (参数1,参数2...){
实现体...
return 返回值;
}
2、如果覆写==,还需要覆写对象的hashCode getter方法,可以工具直接生成
覆写==的代码示例,使用IDE提供的快捷方式
覆写[]中括号的示例
可覆写的操作符列表
操作符复写使用operator关键字
操作符复写在类中的定义格式;
覆写 == 要覆写hashCode getter方法
操作符覆写
覆写操作符需要在类中定义
重写操作符:关键字: operator;
用法: 返回类型 operator 操作符(传递参数){处理的事务}
可以覆写的操作符
操作符覆写
可覆写的操作符
操作符覆写
覆写==,需要同时覆写hashCode
覆写操作符[]
覆写操作符 > code
可覆写的操作符
操作符覆写
操作符覆写
覆写操作符需要在类中定义
返回类型 operator 操作符 (参数1,参数2,....){
实现体..
return 返回值
}
如果覆写 ==,还需要覆写对象的hashcode getter方法

var main(){
Person person1 = new Person(12);
Person person2 = new Person(13);
print( person1 > person2);
}
class Person{
int age;
person(this.age);
bool operator > (Person person){
return this.age > person.age;
}
}
重写 []操作符:对象本身不支持 【】去取出属性的,但是使用操作符可以实现

想要实现对象直接进行大小的比较:只要在该类中进行 operator 复写就行了
