Re: [問題] 不同物件的Link-List

看板C_and_CPP (C/C++)作者 (我要加入劍道社!)時間16年前 (2009/09/26 12:16), 編輯推噓4(402)
留言6則, 5人參與, 最新討論串5/5 (看更多)
※ 引述《godman362 (青)》之銘言: : 不過這樣我又產生了一個問題 : 因為實際上我是根據讀檔案而動態產生不同物件後串連 : 也就是我不知道串連的先後順序,我只知道開頭的位址而已 : 那麼,我的確可以一路往下指下去沒有問題 : 但是假設我要從結構中取值的話,就有問題了 : 因為如同之前所說,我必須要「轉型」 : 可是我不知道目前指的是哪一個,所以也不知道該轉成什麼型態 : 所以想再請問各位,這應該如何解決? : 或是各位有比我更好想法的話,還請指點一下,謝謝 以下是不好的示範 乖孩子請不要學 (雖然這樣的寫法在 C 裡面早已行之多年) typedef enum { LIGHT, TUNELIGHT, WINDOW } StructType; struct Base { struct Base* LocalLink; StructType Type; }; typedef struct Base Base; typedef struct { Base* LocalLink; StructType Type; int Power; } Light; typedef struct { Base* LocalLink; StructType Type; int Power; int Brightness; } TuneLight; typedef struct { Base* LocalLink; StructType Type; int OpenLevel; } Window; // constructors Light* NewLight(int p) { Light* light = (Light*)malloc(sizeof(Light)); light->Type = LIGHT; light->Power = p; light->LocalLink = NULL; return light; } TuneLight* NewTuneLight(int p, int b); // ditto Window* NewWindow(int level); // ditto void foo(Base* list){ Base* next = list; // iterate through the list while(next){ Light* light; TuneLight* tune_light; Window* window; switch(next->Type){ case LIGHT: light = (Light*)next; ... break; case TUNELIGHT: tune_light = (TuneLight*)next; ... break; case WINDOW: window = (Window*)next; ... break; default: // error here exit(1); } next = next->LocalLink; } } 這樣的寫法不好 因為如果你之後要增加更多種類的 struct 必須要改變非常多的地方 而且你不改並不會造成 compile error (這是最糟糕的地方 你很難知道自己到底有沒有改完整) 最正道的方法 是改用 C++ 使用繼承及多型 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.163.147.79

09/26 12:56, , 1F
嗚嗚 公司全都是這種code... 我寫c++還被消遣..
09/26 12:56, 1F

09/26 14:47, , 2F
這種code真是地獄....Orz
09/26 14:47, 2F

09/26 15:05, , 3F
用繼承多型寫起來就不會這麼囉嗦了 眞的方便很多 >"<
09/26 15:05, 3F

09/27 10:13, , 4F
謝謝您的例子,其實我不是一定要用C寫
09/27 10:13, 4F

09/27 10:13, , 5F
只是對多型不熟就是了...
09/27 10:13, 5F

09/27 23:26, , 6F
哀~~~ 莫再提
09/27 23:26, 6F
文章代碼(AID): #1AlPMR7W (C_and_CPP)
文章代碼(AID): #1AlPMR7W (C_and_CPP)