重载操作符的目的:对象与对象之间也可以进行+ - × ÷ -- ++ == | &
等操作
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
}
标签:10,Square,double,height,width,square,操作符,重载,Dart
From: https://www.cnblogs.com/JarryShu/p/17218843.html