繁体   English   中英

继承的 class 中的构造函数?

[英]constructor in inherited class?

我正在了解 C++ 中的 class inheritance 并阅读以下内容:

在构造派生的 class 时,首先构造其基础 class 部分。 操作顺序为:

1) 构建基础 class 成员

2) 调用基础 class 构造函数代码

有人可以解释1和2之间的区别吗? 如何在不调用基本 class 构造函数的情况下构造基本 class 成员? 这不是构造函数的工作吗?

在尝试了解派生 class 构造之前,您应该了解 class 构造。 class 是如何构造的? 在构造 class 时,首先构造其数据成员。 构造函数中的执行顺序是:

  1. 构造了 class 成员。
  2. 构造函数体被调用。

如何在不调用构造函数的情况下构造 class 成员? 它们不是,因为这是构造函数工作的一部分。 构造函数被调用,此时构造函数构造 class 成员,然后构造函数执行其主体(在您正在阅读的任何内容中称为其“代码”)。

MyClass::MyClass()   // <-- entry point for the constructor
                     // <-- construct members
{ /* do stuff */ }   // <-- the body/code

您可以通过初始化列表控制成员构造,也可以使用成员的默认构造。


准备好 inheritance 了吗? 唯一的补充是将基础 class 添加到初始化列表的开头。

Derived::Derived()   // <-- entry point for the derived class constructor
                     // <-- construct base class (see below)
                     // <-- construct members
{ /* do stuff */ }   // <-- the body/code
Base::Base()         // <-- entry point for the base class constructor
                     // <-- construct members (a.k.a. step 1)
{ /* do stuff */ }   // <-- the body/code (a.k.a. step 2)

更复杂,但基本上和以前一样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM