作者holydc (のヮの)
看板C_and_CPP
標題Re: [問題] 繼承與聚合
時間Sat Oct 21 22:23:46 2017
※ 引述《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://webptt.com/m.aspx?n=bbs/C_and_CPP/M.1508595829.A.6B7.html