在 C++ 中调用基类构造函数总是必要的吗?

发布于 2024-09-07 19:51:58 字数 297 浏览 10 评论 0原文

假设我有一些类 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无法言说的痛 2024-09-14 19:51:58

您不需要在派生类型构造函数的初始值设定项列表中指定基类构造函数。当省略它时,将尝试调用不带参数的基本构造函数。如果不存在这样的无参数基本构造函数,那么您将收到编译错误。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文