Dart 重载操作符

重载操作符的目的:对象与对象之间也可以进行+ - × ÷ -- ++ == | & 等操作

class Square {
double? width;
double? height;
Square({required double width,required double height}){
this.width = width < 0 ? 0 : width;
this.height = height < 0 ? 0 : height;
}
/// 返回类型可写可不写,dart会自动推断!
@override
Square operator + (Square square){
var w = (this.width??0) + (square.width??0);//宽加宽
var h = (this.height??0) + (square.height??0);//高加高
return Square(width: w, height: h);
}
}

main(List<String> args) {
Square s1 = Square(width: 10, height: 10);
Square s2 = Square(width: 10, height: 10);
Square s3 = s1 + s2;
print(s1.area());//100
print(s2.area());//100
print(s3.area());//400
}
posted @ 2023-03-15 15:50  勤匠  阅读(61)  评论(0编辑  收藏  举报