gpt4 book ai didi

swift - 来自泛型类型的初始化器不会在 swift 中被继承?

转载 作者:搜寻专家 更新时间:2023-10-30 22:17:43 24 4
gpt4 key购买 nike

这是我的代码:

public class A<T : Any> { 
public init(n : Int) {
print("A")
}
}
public class B : A<Int> {
}
public class C : B {
}
let x = C(n: 123)

编译失败并报错:

repl.swift:9:9: error: 'C' cannot be constructed because it has no accessible initializers

可以编译出如下代码。

public class A { 
public init(n : Int) {
print("A")
}
}
public class B : A {
}
public class C : B {
}
let x = C(n: 123)

需求类型指定泛型类型的初始值设定项不应该被继承吗?

========下面有补充=======

“Superclass initializers are inherited in certain circumstances, but only when it is safe and appropriate to do so. For more information, see Automatic Initializer Inheritance below.”
---Apple Inc. “The Swift Programming Language (Swift 2)” iBooks.

还有这个

“However, superclass initializers are automatically inherited if certain conditions are met.”

“Assuming that you provide default values for any new properties you introduce in a subclass, the following two rules apply:”Rule 1“If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.”Rule 2“If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.”

查看第一个代码时,子类 B没有定义任何指定的初始化器,它应该自动继承它的所有父类(super class)指定的初始化器,那些来自 A<Int> 的.但实际上并没有,这对我来说似乎是有线的。

最佳答案

那个怎么样??我尝试使用override code和super.init,没有报错。我认为您不必使用泛型类型初始化函数。

尝试在 B 类和 C 类中放置 override init 函数。看起来像这样,

public override init(n:Int) {
super.init(n: n)
}

关于swift - 来自泛型类型的初始化器不会在 swift 中被继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34525368/

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