gpt4 book ai didi

swift - 方法不会覆盖其父类(super class)中的任何方法(Swift 4、Xcode 9)

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

我检查了一些与同一问题相关的主题,但我在自己的代码中找不到此问题的任何解决方案...

当我尝试重写 Piano: Instrument 子类中的函数tune() 时,会发生错误。

我复制/粘贴了父类(super class)原始函数,以确保语法严格相同。

此外,在我看来,子类做得很好,因为 super.init 方法似乎按预期工作(没有编译器错误)。

请问有人可以指出我的错误在哪里吗?

代码:

class Music {

let notes: [String]

init(notes: [String]) {
self.notes = notes
}

func prepared() -> String {
return notes.joined(separator: " ")
}

}

class Instrument {

let model: String

init(model: String) {
self.model = model

func tune() -> String {
fatalError("Implement this method for \(model)")
}

func play(_ music: Music) -> String {
return music.prepared()
}

func perform(_ music: Music) {
print(tune())
print(play(music))
}

}

}

class Piano: Instrument {

let hasPedals: Bool

init(hasPedals: Bool, model: String) {
self.hasPedals = hasPedals
super.init(model: model)

}

override func tune() -> String {
fatalError("Implement this method for \(model)")
}

}

class Guitar: Instrument {

let hasAmplifyer: Bool

init(hasAmplifyer: Bool, model: String) {
self.hasAmplifyer = hasAmplifyer
super.init(model: model)

}

}

非常感谢!

最佳答案

您不小心在 init 函数中定义了 tuneplayperform 函数。将它们移至顶层:

class Instrument {

let model: String

init(model: String) {
self.model = model
}

func tune() -> String {
fatalError("Implement this method for \(model)")
}

func play(_ music: Music) -> String {
return music.prepared()
}

func perform(_ music: Music) {
print(tune())
print(play(music))
}

}

Swift 认为没有要重写的 tune 函数,因为它希望它位于 Instrument 中的顶层。

关于swift - 方法不会覆盖其父类(super class)中的任何方法(Swift 4、Xcode 9),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46551542/

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