Swift语言精要 - Operator(运算符重载)

运算符重载

Swift的这一语言特性或许应该启发于C++

class Vector2D {
    var x : Float = 0.0
    var y : Float = 0.0
    init (x : Float, y: Float) {
        self.x = x
        self.y = y
    }
    func +(left : Vector2D, right: Vector2D) -> Vector2D {
        let result = Vector2D(x: left.x + right.x, y: left.y + right.y)
        return result
    }
}

测试代码如下:

let first = Vector2D(x: 2, y: 2)
let second = Vector2D(x: 4, y: 1)
let result = first + second
// = (x:6, y:3)

 

posted @ 2016-04-01 19:33  Master HaKu  阅读(390)  评论(0编辑  收藏  举报