85人参与 • 2025-05-06 • C/C++
在 kotlin 里,运算符重载函数允许为自定义类型重新定义现有的运算符(如 + -…)行为,从而让自定义类型能像内置类型那样使用运算符
若要重载运算符,需要定义一个带有 operator 修饰符的函数。函数名必须是 kotlin 预定义的运算符对应的函数名。基本语法如下:
class yourclass {
operator fun xxx(parameters): returntype {
// 函数体
}
}比如为我们的自定义类型添加加法运算
如下图所示:+对应的函数名是plus,+=对应的函数名是 plusassign

class student(val name: string, val age: int) {
//注意,二元运算符必须带一个形参,表示右侧的操作数
operator fun plus(another: student): student {
return student(this.name + another.name, this.age+another.age)
}
}
fun main() {
val stu1 = student("海贼王 ", 2)
val stu2 = student("我当定了", 4)
val result = stu1 + stu2
println("(${result.name}, ${result.age})")
}
在这个例子中,student类重载了 + 运算符,实现了两个 student对象的相加。stu1 + stu2相当于stu1.plus(stu2)
接下来举一个重载一元运算符的例子,比如取反运算符:
class student(val name: string, val age: int) {
operator fun not(): student {
return student(name.reversed(), age)
}
}
fun main() {
val stu1 = student("海贼王", 2)
val stu2 = !stu1
println("(${stu2.name}, ${stu2.age})")
}
!stu1相当于stu1.not()
尽管基本数据类型(如 int、double 等)的内置运算符已有默认行为,但可以为它们的扩展类型定义新的运算符行为。
// 为 int 类型的扩展类重载 * 运算符
class multiplier(val value: int) {
operator fun times(other: int): int {
return this.value * other
}
}
fun main() {
val multiplier = multiplier(5)
val result = multiplier * 3
println(result)
}在上述代码中,为 multiplier 类重载了 * 运算符,让 multiplier 对象可以和 int 类型的数据进行乘法运算。
如果一个类实现了特定的接口,并且接口中定义了运算符重载函数,那么该类对象也能使用这些重载的运算符。
interface addable<t> {
operator fun plus(other: t): t
}
class complexnumber(val real: double, val imaginary: double) : addable<complexnumber> {
override operator fun plus(other: complexnumber): complexnumber {
return complexnumber(this.real + other.real, this.imaginary + other.imaginary)
}
}
fun main() {
val c1 = complexnumber(1.0, 2.0)
val c2 = complexnumber(3.0, 4.0)
val result = c1 + c2
println("(${result.real}, ${result.imaginary})")
}在这个例子中,complexnumber 类实现了 addable 接口,并重载了 + 运算符,使得 complexnumber 对象可以使用 + 进行相加操作。
到此这篇关于kotlin-运算符重载函数的文章就介绍到这了,更多相关kotlin运算符重载函数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论