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)

转载于:https://www.cnblogs.com/davidgu/p/5346075.html

猜你喜欢

转载自blog.csdn.net/weixin_34384915/article/details/93803055