为什么要调用基础构造函数?
有这样的代码:
class A
{
public A(int x)
{}
}
class B:A
{
public B(int x):base(3)
{}
}
我不明白。 B类是A类的独立子类,为什么我需要调用它的构造函数?我很困惑,因为看起来 A 的实例是在我创建 B 的实例时创建的。
Having code like this:
class A
{
public A(int x)
{}
}
class B:A
{
public B(int x):base(3)
{}
}
I do not get it. The class B is independent child of class A, why I need to call its constructor? I am confused as it looks like the instance of A is created when I create instance of B..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
调用基类构造函数可以初始化从基类继承的内容。
Calling the base class constructor lets you initialize things you're inheriting from the base class.
类
B
不独立于类A:它继承类A
,因此是该类的“扩展”班级。创建
B
时,不会创建单独的A
实例;A
的功能是您正在创建的内容的一部分。调用A
的构造函数允许在必要时初始化该功能。Class
B
is not independent of class A: it inherits classA
and is thus an "extension" of that class.You don't create a separate instance of
A
when you createB
; the functionality ofA
is part of what you're creating. CallingA
's constructor allows that functionality to initialize if necessary.如果不调用基本构造函数,A 如何知道 B 中的
int x
与 A 中的int x
相同?If you don't call the base constructor, how is A supposed to know that the
int x
in B is the sameint x
as in A?类 A 没有无参数构造函数,因此必须从 B 的构造函数中调用 A(int x)。
Class A has no parameterless constructor, hence you have to call A(int x) from the constructor of B.
B 继承自 A,因此当您创建 B 的实例时,它也是 A,因此需要调用 A 的构造函数来进行任何初始化。
B inherits from A, so when you create an instance of B it is also an A, so the constructor for A needs to be called to do any initialisation.
原因是基于类定义它的构造函数需要一个参数。您正在继承,因此您必须尊重
A
的要求。Reason is based class defines that it requires a parameter for its constructor. You are inheriting so you will have to respect requirements of
A
.当您创建派生类的实例时,您总是必须调用基构造函数,没有办法绕过它。但是,如果基类具有无参数构造函数,则不必指定对基构造函数的调用,如果将其省略,它将隐式调用无参数构造函数。如果基类没有无参数构造函数(如您的示例中所示),则必须指定要调用哪个基构造函数以及要向其发送哪些参数。
当您创建类
B
的实例时,您有点创建了类A
的实例,因为B< /code> 实例是 一个
A
实例。必须调用基类中的构造函数来初始化您可能继承的任何成员。该对象首先初始化为A
实例,然后初始化为B
实例。When you create an instance of a derived class, you always have to call the base constructor, there is no way around it. However, if the base class has a parameterless constructor, then you don't have to specify the call to the base constructor, if you leave it out it will implicitly call the parameterless constructor. If the base class has no parameterless constructor (like in your example), you have to specify which base constructor to call, and what parameters to send to it.
When you create an instance of the class
B
, you are kind of creating an instance of the classA
, because theB
instance is anA
instance. The constructor in the base class has to be called to initialise any members that you might inherit. The object is first initialised as anA
instance, then as aB
instance.A 的实例是在创建 B 时创建的,因为 B 继承了实例 A
The instance of A is created when you create B as B inherits instance A