Re: [問題] 繼承與聚合

看板C_and_CPP (C/C++)作者 (のヮの)時間8年前 (2017/10/21 22:23), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《dwight90488 (陳佳佳)》之銘言: : 開發平台(Platform): (Ex: Win10, Linux, ...) : Win7 : 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) : C++ : 問題(Question): : 想請問大大們 繼承與聚合的建構方式 : Class:樂器 聚合 Class:樂器規格(InstrumentSpec) : ------------------------------ <------ ------------------------------- : 成員:序號(string) 型號(string) : 價格(double) 材質(string) : 樂器規格(InstrumentSpec) : ^ ^ : | | : | 繼承 | 繼承 : | | : Class:吉他 聚合 Class:吉他規格(GuitarSpec) : ------------------------------ <------ ------------------------------- : 吉他規格(GuitarSpec) 弦數(int) : 樂器的constructor: 樂器(string 序號, double 價格, InstrumentSpec 樂器規格); : 樂器規格的constructor: 樂器規格(string 型號, string 材質) : 吉他規格的constructor: 吉他規格(string 型號, string 材質, int 弦數) : 這時候我就有點困惑有關於吉他的contructor的撰寫方式 : 這是我目前想到可行的建構子 : 吉他的contructor: 吉他(string 序號, doble 價格, GuitarSpec 吉他規格) : :樂器(序號, 價格, 吉他規格),吉他規格(吉他規格) : 這樣建構是正確的嗎? 感覺樂器initializer的規格那部分可以移掉, : 畢竟後面吉他規格已經有初始化到了.... : 還是有正確的建構方式呢? 先謝謝您們的回答了!!!! 就我看來這樣的設計沒什麼問題,類似 bridge pattern 但是因為所有的樂器都有規格 依照個人拙見,不該是移除樂器初始化規格的部分 反而是樂器的實作不需要再擁有自己的規格 也就是 Guitar 不用和 GuitarSpec 聚合 因為 Instrument 的 InstrumentSpec 成員指標就可以指向 GuitarSpec 的實體 野人獻曝的話大概會像這樣(其實跟你的幾乎一樣) class Instrument { public: Instrument(string serial, double price, InstrumentSpec *spec) : serial_(move(serial)), price_(price), spec_(spec) { } private: string serial_; double price_; InstrumentSpec *spec_; }; class Guitar : public Instrument { public: Guitar(string serial, double price, GuitarSpec *spec) : Instrument(move(serial), price, spec) { } // no additional members }; 不過根據你開的介面,Guitar 在使用 spec_ 的時候可能有需要轉型成 GuitarSpec * 以 OOP 來說會稍微醜一點(imho) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.169.114.60 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1508595829.A.6B7.html
文章代碼(AID): #1PwrXrQt (C_and_CPP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #1PwrXrQt (C_and_CPP)