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的初始化方式,而非在自己的建構式主體內直接賦值給那些成員。』

紀錄之。

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *