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 還可以了解,但是這個複合有關係嗎?還沒有很清楚?

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

點我分享到Facebook

發佈留言

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