构造函数继承
我试图理解但仍然不确定。如果基类中有构造函数,派生类总会调用它吗?我知道他们可以重写它(这里不是正确的术语,我知道 - 我的意思是向其构造函数添加代码),但我假设如果构造函数是在基类中定义的,则派生类将始终调用它。这是真的吗?
I have tried to understand but still not sure. If there is a constructor in the base class, the derived classes will always call it? I know they can override it (not correct term here, I know - I mean add code to their constructors) but I assume if the constructor is defined in the base class, the derived ones will always call it. Is that true?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,如果有无参数构造函数,它将始终被调用。如果有多个构造函数,您可以使用
base
关键字:如果没有无参数构造函数,您将被迫这样做:
Yes, if there is a parameterless constructor it will always be called. If there is more than one constructor, you can choose which one to call with the
base
keyword:If there is no parameterless constructor, you will be forced to do this:
如果基类中只有无参数构造函数,则子类构造函数将始终首先称为。另一方面,如果您在基类中定义了其他构造函数,则儿童类将有一个选项要拨打的基础构造函数。
If there is only a parameterless constructor in the base class, the child class constructor will always call it first. On the other hand if you have other constructors defined in the base class, then the child class will have an option which base constructor to call.