gpt4 book ai didi

swift - 如何创建子类对象?

转载 作者:行者123 更新时间:2023-11-28 11:37:29 24 4
gpt4 key购买 nike

不幸的是,我的代码一次又一次地收到错误消息 'self' used in property access 'healthPoints before 'super.init' call:

头等舱单元

import UIKit
import SpriteKit

class Unit {

// var gameScene : GameScene!

var healthPoints = 10
var damage = 5
var movement = 1

init(pHealthPoints: Int, pDamage: Int,pMovement: Int) {

self.healthPoints = pHealthPoints
self.damage = pDamage
self.movement = pMovement
}


required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

}

子类骑士

import UIKit
import SpriteKit

class Knight: Unit {

override init(pHealthPoints: Int, pDamage: Int, pMovement: Int) {

self.healthPoints = pHealthPoints
self.damage = pDamage
self.movement = pMovement

}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

}

super 到底应该写在子类的什么地方?

如何通过 GameScene.swift 访问类 Unit 或类 Knight创建对象 属于 Knight 类?

对于每一个回答我都非常感激

最佳答案

您只需调用 super.init 即可为子类的属性赋值。也不需要实现 init?(coder aDecoder: NSCoder)。另请记住,您重写的 init 方法实际上与 super 实现没有任何不同,因此重写它没有意义。

class Knight: Unit {

override init(pHealthPoints: Int, pDamage: Int, pMovement: Int) {
super.init(pHealthPoints: pHealthPoints, pDamage: pDamage, pMovement: pMovement)
self.healthPoints = pHealthPoints
self.damage = pDamage
self.movement = pMovement
}
}

关于swift - 如何创建子类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54678886/

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