gpt4 book ai didi

swift - Swift 中的运算符优先级重载

转载 作者:搜寻专家 更新时间:2023-10-31 08:14:26 24 4
gpt4 key购买 nike

在为自定义类重载运算符时,有什么方法可以覆盖运算符优先级吗?在我的示例中,+ 的优先级应该高于 *。我可以覆盖默认的运算符优先级吗?

class Vector{
var x:Int
var y:Int
init(x _x:Int, y _y:Int){
self.x = _x
self.y = _y
}
}

func *(lhs:Vector, rhs:Vector)->Int{
return lhs.x * rhs.y + rhs.x + rhs.y
}

func +(lhs:Vector, rhs:Vector)->Vector{
return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}

var v1 = Vector(x: 6, y: 1)
var v2 = Vector(x: 3, y: 1)


v1 * v2 + v1

最佳答案

嗯。实际上看起来你可以。

operator infix + { associativity left precedence 140 }
operator infix * { associativity left precedence 30 }

let x = 3 + 4 * 5 // outputs 35

但据我所知,这只能在“文件范围”内完成,至少根据将其包含在类中所产生的编译器错误来看是这样。

'operator' may only be declared at file scope.

关于swift - Swift 中的运算符优先级重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24316882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com