首頁 / CompScience / Programming / Languages / C_and_CPP / Respecting the Base-Class Interface

Respecting the Base-Class Interface

C++ Primer 4/e在Defining Base and Derived Classes這個地方有一個關鍵概念:『The reason that a constructor can initialize only its immediate base class is that each class defines its own interface. When we define Disc_item, we specify how to initialize a Disc_item by defining its constructors. Once a class has defined its interface, all interactions with objects of that class should be through that interface, even when those objects are part of a derived object.

For similar reasons, derived-class constructors may not initialize and should not assign to the members of its base class. When those members are public or protected, a derived constructor could assign values to its base class members inside the constructor body. However, doing so would violate the interface of the base. Derived classes should respect the initialization intent of their base classes by using constructors rather than assigning to these members in the body of the constructor.』

中文版的這樣寫:『建構式只能初始化直接繼承的base class,因為每個class都定義了自己的介面。當我們定義Disc_item,我們定義其建構式,指明如何初始化Disc_item。一旦class定義其介面,所有與該class物件的任何互動都應該透過其介面進行,即便這些物件是derived 物件的一部分。

基於類似原因,derived class建構式不能對其base class成員進行初始化,也不該對它們賦值。如果這些成員是public或protected,derived建構式(就語法而言)可在函式主體內賦值給其base class成員。然而這麼做會違反base介面。Derived classes應該改用建構式,遵從其base classes的初始化方式,而非在自己的建構式主體內直接賦值給那些成員。』

紀錄之。

Print Friendly, PDF & Email
馬上成為工作達人的Fans

About ㄚ琪

工作達人Fun Taiwan的創辦者及總編,可以在這裡更認識他。

發表迴響

你的電子郵件位址並不會被公開。 Required fields are marked *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

Scroll To Top