//运算符重载定义
//任意类可以定义或者重载父类的基本运算符
//通过运算符的具名函数定义
//
//重载运输符 方法名称 参数个数要对应 参数类型和返回值可以随意定义
class Complex(var real:Double,var imaginary:Double){
//
operator fun plus(other:Complex):Complex{//定义运算符
return Complex(real+other.real,imaginary+other.imaginary)
}
operator fun plus(a:Int):Complex{//定义运算符 可以定义参数类型
return Complex(real,imaginary+a)
}
operator fun plus(other:Any):Int{//定义运算符 可以随意定义返回值
return real.toInt()
}
operator fun invoke():Double{
return Math.hypot(real,imaginary)
}
override fun toString(): String {
return "${real} ${imaginary}i"
}
}
class Book{
infix fun on(a:Any):Boolean{//定义中缀表达式
return false
}
}
class Desk
fun main(args:Array<String>){
val c1 = Complex(3.0,4.0)
val c2 = Complex(2.8,3.4)
println(c1+c2)//
println(c1+5)
println(c1())//取模运算
println(Book() on Desk())//infix定义中缀表达式 不需要.方法名 可以作为运算符使用
}
kotlin运算符重载
最新推荐文章于 2025-07-16 15:49:56 发布

9881

被折叠的 条评论
为什么被折叠?



