讓已有的運(yùn)算符對自定義的類和結(jié)構(gòu)進(jìn)行運(yùn)算或者重新定義已有運(yùn)算符的運(yùn)算規(guī)則夫否,這種機(jī)制被稱為運(yùn)算符重載。
1.通過重載加號運(yùn)算符岖是,使自定義的兩個坐標(biāo)結(jié)構(gòu)體對象實(shí)現(xiàn)相加
struct CenterPointer {
var x = 0, y = 0
}
func + (left: CenterPointer, right: CenterPointer) ->CenterPointer {
return CenterPointer(x: left.x+right.x, y: left.y+right.y)
}
let pointer1 = CenterPointer(x: 1, y: 3)
let pointer2 = CenterPointer(x: 2, y: 3)
let pointer3 = pointer1 + pointer2
print(pointer3) // 打印結(jié)果 CenterPointer(x: 3, y: 6)
2.重載判斷運(yùn)算符棉圈,實(shí)現(xiàn)判斷自定義類型是否相等
func == (left: CenterPointer, right: CenterPointer) ->Bool {
return left.x == right.x && left.y == right.y
}
func != (left: CenterPointer, right: CenterPointer) ->Bool {
return !(left == right)
}
3.組合運(yùn)算符幌氮,即將其他運(yùn)算符和賦值運(yùn)算符組合在一起,注意要把運(yùn)算符左參數(shù)設(shè)置成inout類型
func += (left: inout CenterPointer, right: CenterPointer) {
left = left + right
}
//var pointer1 = CenterPointer(x: 1, y: 3)
//var pointer2 = CenterPointer(x: 2, y: 3)
//pointer1 += pointer2
//print(pointer1) // 打印結(jié)果 CenterPointer(x: 3, y: 6)