kotlin运算符重载


//运算符重载定义
//任意类可以定义或者重载父类的基本运算符
//通过运算符的具名函数定义
//
//重载运输符 方法名称  参数个数要对应 参数类型和返回值可以随意定义

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定义中缀表达式 不需要.方法名  可以作为运算符使用
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值