假设我有一个猫类,我做了两个例子。我要猫能互相攻击
class ninjaCat {
var health : Double = 100.00
var attack = Double()
init(attack : Double){
self.attack = attack
}
func thunderClaw(otherCat : ninjaCat){
health = otherCat.health
otherCat.health = health - self.attack
}
}
var NinjaCat1 = ninjaCat(10.60)
var NinjaCat2 = ninjaCat(20.15)
NinjaCat1.thunderClaw(NinjaCat2)
是否可以将类对象作为函数参数传递?
最佳答案
这确实是可能的。但是,您应该检查代码,因为您使用攻击猫的当前寿命而不是目标的寿命来计算剩余寿命:
func thunderClaw(otherCat : ninjaCat){
otherCat.health = health - self.attack
}
应该是
func thunderClaw(otherCat : ninjaCat){
otherCat.health = otherCat.health - self.attack
}
或者简单地说
func thunderClaw(otherCat : ninjaCat){
otherCat.health -= self.attack
}