英文:
Dart super-initializer constructor with private members
问题
I'm currently learning Dart and have just written a class which extends a Base and uses the "super.* syntax" to initialize it. The member variable of the base which gets initialized is private and therefore prefixed with an underscore.
class X {
final int _i;
X(this._i);
}
class Y extends X {
Y(super.i);
}
For some reason though the compiler is happy with me omitting the underscore in the derived class. Why? Omitting it in the base generates a compiler error.
英文:
I'm currently learning Dart and have just written a class which extends a Base and uses the "super.* syntax" to initialize it. The member variable of the base which gets initialized is private and therefor prefixed with an underscore.
class X {
final int _i;
X(this._i);
}
class Y extends X {
Y(super.i);
}
For some reason though the compiler is happy with me omitting the underscore in the derived class. Why? Omitting it in the base generates a compiler error.
答案1
得分: 2
Y(super.i)
并不使用 name i
以外的任何内容,仅用于文档说明。参数是位置参数,它会在不考虑名称的情况下转发到超类构造函数中的相同位置。你可以声明它为 Y(super.arglebargle)
,它将同样有效。
命名参数会使用它们的名称,因此只有在位置参数的情况下才能编写任何内容。
英文:
The Y(super.i)
doesn't use the name i
for anything other than documentation.
The parameter is positional, and it's forwarded to the same position in the superclass constructor without looking at the name at all. You could declare it Y(super.arglebargle)
and it would work just the same.
Named parameters do use their names, so it's only for positional super-parameters that you can write anything.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论