gpt4 book ai didi

swift - 开放类公共(public)成员函数

转载 作者:搜寻专家 更新时间:2023-11-01 05:34:10 24 4
gpt4 key购买 nike

我在 Swift 中有一个 Shapes 模块,包括 Shape 类。我刚刚打开了一个新的 Playground 并将这个模块添加到源文件中。 playground 中的 Square 类可以继承 Shapes 模块中的 Shape 类。没有问题,但是 Shape 类中的公共(public)方法在 Square 类中被覆盖了。

根据 swift 消息来源,执行继承时只能重写开放成员函数。

也许这是一个非常基本的问题,所以我已经很抱歉提出这个问题了。

这是一个示例 Playground 代码,当 ParentChild 定义在不同的模块中时,行为是相同的:

open class Parent {
public init() { print("Parent init") }
public func foo() { print("Parent foo") }
open func bar() { print("Parent bar") }
}

class Child: Parent {
override init() { print("Child init") }
override func foo() { print("Child foo") }
override func bar() { print("Child bar") }
}

let child = Child()
child.foo()
child.bar()

输出:

Child init
Parent init
Child foo
Child bar

最佳答案

  1. 您应该在帖子中包含您尝试过的代码。

  2. “执行继承时只能覆盖开放成员函数”,我不认为Apple doc说。以下是公开课和公开课的区别:

Open access applies only to classes and class members, and it differs from public access as follows:

  • Classes with public access, or any more restrictive access level, can be subclassed only within the module where they’re defined.
  • Class members with public access, or any more restrictive access level, can be overridden by subclasses only within the module where they’re defined.
  • Open classes can be subclassed within the module where they’re defined, and within any module that imports the module where they’re defined.
  • Open class members can be overridden by subclasses within the module where they’re defined, and within any module that imports the module where they’re defined.

关于swift - 开放类公共(public)成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45544333/

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