簡體   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