实例成员不能用于Class类型吗? [英] Instance member cannot be used on type Class?
问题描述
我正在尝试从Indicator类访问name
变量,该类继承自Person.但是,我认为我没有正确地进行初始化.
I'm trying to access the name
variable from Indicator class, which inherits from Person. However, I believe I'm not doing my initialization right.
我得到以下信息:'错误:实例成员'name'不能用于'Indicator'`类型.
I get the following: 'error: instance member 'name' cannot be used on type 'Indicator'`.
class Person {
var name: String
init(myName: String){
self.name = myName
}
deinit {
Indicator.letKnowPersonDeinitialized()
}
}
class Indicator: Person {
convenience init() {
self.init()
}
static func letKnowPersonDeinitialized() {
print("\(name)")
}
}
推荐答案
您不能直接在静态方法中访问非静态内容.
You cannot access non-static stuff directly in a static method.
方法letKnowPersonDeinitialized
是静态的,因为它已使用static
修饰符进行了修改:
The method letKnowPersonDeinitialized
is static because it is modified with the static
modifier:
static func letKnowPersonDeinitialized() {
^
|
here!
}
Person
的name
属性不是静态的,因为它没有被static
修改.
The name
property of Person
is not static because it is not modified by static
.
由于非静态成员属于该类的每个单独实例,而静态成员属于该类本身,因此静态成员无法直接访问非静态成员.他们只能在存在实例的情况下访问非静态成员.
Since non-static members belong to each individual instance of that class and static members belong to the class itself, static members have no direct access to non-static members. They can only access non-static members when an instance is present.
要解决您的问题,请在letKnowPersonDeinitialized
方法中添加一个参数:
To solve your problem, add a parameter to the letKnowPersonDeinitialized
method:
static func letKnowPersonDeinitialized(person: Person) {
print(person.name)
}
然后在反初始化器中:
deinit {
Indicator.letKnowPersonDeinitialized(self)
}
非常重要的东西:
我认为您的代码设计得不好.这不是您使用继承的方式.
VERY IMPORTANT STUFF:
I don't think your code is designed well. This is not how you use inheritance.
继承表示是一种".因此,如果Indicator
继承自Person
,则意味着指标是一种人.
Inheritance means "is a kind of". So if Indicator
inherits from Person
, it means that an indicator is a kind of person.
根据常识,指标不是人.因此,此处不适合使用继承.没什么意义.
According to common sense, an indicator is not a person. Therefore, it is not suitable to use inheritance here. It makes little sense.
这篇关于实例成员不能用于Class类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!