輸入優惠碼現折100元
首頁 / CompScience / Programming / Languages / C_and_CPP / Inheritance versus Composition

Inheritance versus Composition

C++ Primer 4/e在Defining Base and Derived Classes這個地方有一個關鍵概念:『The design of inheritance hierarchies is a complex topic in its own right and well beyond the scope of this language primer. However, there is one important design guide that is so fundamental that every programmer should be familiar with it.

When we define one class as publicly inherited from another, the derived class should reflect a so-called “Is A” relationship to the base class. In our bookstore example, our base class represents the concept of a book sold at a stipulated price. Our Bulk_item is a kind of book, but one with a different pricing strategy.

Another common relationship among types is a so-called “Has A” relationship. Our bookstore classes have a price and they have an ISBN. Types related by a “Has A” relationship imply membership. Thus, our bookstore classes are composed from members representing the price and the ISBN.』

中文版的這樣寫:『「繼承體系的設計」是一個值得獨立探討的主題,遠超過作為語言初階教本的本書範疇。然而有個十分重要的設計準則,重要到每個程式員都應該熟悉它。

當我們把class定義為「以public形式繼承自另一個class」,derived class和base class之間應該反映出所謂的”IS A”關係。在書店例子中,base class代表「以定價售出的書籍」,Bulk_item也是一種書,但有不同的價格策略。

另一個常見的型別關係是”Has A”。書店例中的classes有一個價錢,也有一個ISBN。型別之間的”Has A”關係即代表成員從屬關係。書店classes由價格成員和ISBN成員組成。』

IS A 跟 Has A 還可以了解,但是這個複合有關係嗎?還沒有很清楚?

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

About ㄚ琪

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

發表迴響

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

*

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

Scroll To Top