gpt4 book ai didi

constructor - 无法编译内部构造函数调用原因 :Primary constructor call expected

转载 作者:行者123 更新时间:2023-12-02 12:07:19 30 4
gpt4 key购买 nike

假设我们有以下主要和次要构造函数:

open class Animal(val name:String){
internal constructor(message:InputStream): this(readName(message))
}

为什么不能调用父类(super class)的内部构造函数?
class Dog(name:String):Animal(name){
internal constructor(message:InputStream):super(message)
^^^^^
Primary constructor call expected
}

编辑

显然,当主构造函数转换为辅助构造函数或完全删除时,它会编译。
class Dog:Animal{
constructor(name:String):super(name)
internal constructor(message:InputStream):super(message)

}

这是编译器错误吗?

最佳答案

来自 docs :

If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s). Delegation to another constructor of the same class is done using the this keyword



和:

If the class has no primary constructor, then each secondary constructor has to initialize the base type using the super keyword, or to delegate to another constructor which does that.



您的 Dog类有一个主构造函数,所以你必须使用 this 委托(delegate)给它.
如果去掉主构造函数,可以引用 super构造函数:
class Dog : Animal {
constructor(message: InputStream) : super(message)
}

(以上没有错误)

关于constructor - 无法编译内部构造函数调用原因 :Primary constructor call expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52947945/

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