在 C++ 中调用基类构造函数总是必要的吗?
假设我有一些类 C
,我继承它并将该类命名为 D
。我是否总是需要调用 C
的默认构造函数,如本例所示:
class C {
public:
C() { ... }
};
class D {
public:
D() : C() { ... }
};
请注意,C
只有默认构造函数。我必须从 D 调用它吗?我不知道如何找到这个。
谢谢,博达·西多。
Suppose I have some class C
, and I inherit from it and name this class D
. Do I always have to call C
's default constructor as in this example:
class C {
public:
C() { ... }
};
class D {
public:
D() : C() { ... }
};
Note that C
has only the default constructor. Do I have to call it from D? I couldn't figure out how to find this out.
Thanks, Boda Cydo.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要在派生类型构造函数的初始值设定项列表中指定基类构造函数。当省略它时,将尝试调用不带参数的基本构造函数。如果不存在这样的无参数基本构造函数,那么您将收到编译错误。
You don't need to specify the base class constructor in your derived type constructor's initializer list. When it is omitted an attempt will be made to call the base constructor with no parameters. If no such parameterless base constructor exists, then you'll get a compiling error.