Kotlin实现复数类的基本操作

1.加法

2.减法

3.乘法

运算符重载

package javax

class Complex {

    private var real:Int = 0
    private var image:Int = 0

    constructor()

    constructor(real:Int,image:Int) {
        this.real = real
        this.image = image
    }

    operator fun plus(c:Complex):Complex{
        return Complex(c.real + real,c.image+image)
    }

    operator fun minus(c:Complex):Complex{
        return Complex(c.real - real,c.image-image)
    }

    operator fun times(c:Complex):Complex{
        return Complex(this.real*c.real-this.image*c.image,this.image*c.real+this.real+c.image)
    }

    override fun toString(): String {
        val img = if (image>=0) "+ ${image}i" else "${image}i"
        return "$real $img"
    }



}
fun main(args:Array<String>) {
    val c1 = Complex(1,1)
    val c2 = Complex(2,2)
    println(c1)
    println(c2)
    println(c1+c2)
    println(c1-c2)
    println(c1*c2)
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容