gpt4 book ai didi

ios - 类继承、覆盖方法和从父类(super class)访问存储的属性

转载 作者:可可西里 更新时间:2023-11-01 00:52:09 26 4
gpt4 key购买 nike

我正在学习 Swift 和面向对象的编程,过去一周我一直在进行“测验”。我的任务是创建一个名为 Robot 的 Machine 子类,然后覆盖父类(super class)的 move 方法,这样当我输入一个特定的字符串时,机器人移动(向上 - y++,向下 - y--,向右 - x++,向左 - y --)

class Point {
var x: Int
var y: Int

init(x: Int, y: Int){
self.x = x
self.y = y
}
}

class Machine {
var location: Point

init() {
self.location = Point(x: 0, y: 0)
}

func move(direction: String) {
print("Do nothing! I'm a machine!")
}
}

我真正纠结的是如何覆盖移动方法。这是我的思考过程 - 请纠正我错误的地方:

//The Robot class inherited the location stored property from its superclass; this property includes x and y as its of type Point
//x and y are already initialized in Robot because they're initialized in its super class
//I need to OVERRIDE the move method, so I cannot add x and y to the method's parameters or add a return type
//Therefore, I need to affect x and y without passing them into the method as arguments... and this is where I'm lost

这是我认为需要发生的事情的总体思路:

class Robot: Machine {
let isRobot: Bool = true

override func move(direction: String) {
switch direction {
case "Up":
y++
case "Down":
y--
case "Right":
x++
case "Left":
x--
default:
break
}
}
}

如果甚至有可能影响方法中的 x 和 y 而无需将它们作为参数传递,我已经尝试过 self.location = Point(x: x+1, y) 和 self.location += Point.x 没有成功。这些对我来说是新概念,非常感谢任何帮助!

最佳答案

你们非常非常接近。您唯一的错误是 xy 不是 Machine 的属性。它们是 Machine.location 的属性。

你的 self.location = Point(x: x+1, y) 应该可以工作,所以我很好奇“没有成功”是什么意思。更简单的方法与您所做的完全相同,但修改位置:

     case "Up":
location.y++

可能不相关,但是您的 Point 可以更好地实现为 struct 而不是 class。使用 Point 作为可变引用类型(包含 var 属性的类)会导致很多困惑。如果两个 Robot 实例传递相同的 Point,那么对一个的修改也会修改另一个,这将是非常令人惊讶的。另一方面,struct 是一种值类型。如果您将它传递给某物,接收者将获得自己的副本。

引用类型(类)最好在事物具有身份和自己的状态时使用。同一位置的两个机器人仍然是不同的机器人。但是在同一位置的两个点是同一个点。这意味着点是值,应该是一个 struct

关于ios - 类继承、覆盖方法和从父类(super class)访问存储的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34271402/

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