[問題] Stack(linked-list) with template

看板C_and_CPP (C/C++)作者 (涅斯塔尼歐)時間15年前 (2010/12/16 16:13), 編輯推噓1(1010)
留言11則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, Gcc, Linux, ...) DEV C++ 問題(Question): 我在書上看到用template去做Stack,資料處理的方式是Dynamic Array。 而我想說試試看用template去處理linked-list做成的Stack。 不過目前碰到一個我實在想不通的問題。 程式碼(Code): (請善用置底文標色功能) template <typename StackElement> class Stack { ..... private: class Node { public: StackElement data; Node *next; Node(StackElement value, Node *link=0):data(value), next(link){} }; typedef Node* NodePointer; NodePointer mytop; }; template <typename StackElement> Stack<StackElement>::Stack(const Stack<StackElement> &original) { .... mytop = new Stack<StackElement>::Node(original.top()); // 這行出錯 .... } 跑出的訊息是 'class Stack<StackElement>::Node' is not a type 還有後面有很多地方也跑出類似的訊息,像是 template <typename StackElement> Stack<StackElement>::~Stack() { Stack<StackElement>::NodePointer currPtr = mytop, nextPtr; while(currPtr != 0) { nextPtr = currPtr->next; // 這行出錯 .... } } 它顯示 'nextPtr' undeclared (first use this function) 補充說明(Supplement): 我是在想,是不是因為class Stack裡面的class Node不能用 Stack<StackElement>::Node 這樣的語法呢? 因為書上沒有這樣的範例,我就自己試過幾種排列組合, 不過錯誤訊息仍然存在。 請問是哪邊出錯了呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.118.44.32

12/16 16:37, , 1F
加上 typename 關鍵字, 你不加他會當成static member
12/16 16:37, 1F

12/16 16:43, , 2F
而不是一個型態
12/16 16:43, 2F

12/16 20:07, , 3F
好像typedef放在template裡常常會發生這種事,不知道
12/16 20:07, 3F

12/16 20:07, , 4F
typedef的意義是什麼?和typename相比有什麼不同?
12/16 20:07, 4F

12/16 20:25, , 5F
在檢查模板語法的時候, 編譯器並不知道你::左邊型態的
12/16 20:25, 5F

12/16 20:26, , 6F
詳細資訊, 所以也就當然不知道::右邊到底是什麼東西
12/16 20:26, 6F

12/16 20:27, , 7F
他只能"猜"這是一個靜態成員, 你不明確跟他講「這是一
12/16 20:27, 7F

12/16 20:28, , 8F
種型態」他當然會報錯
12/16 20:28, 8F

12/16 20:28, , 9F
typedef 是為型態取另一個名字, typename 是跟編譯器
12/16 20:28, 9F

12/16 20:29, , 10F
講後面接著的東西是一種型態, 這兩個關鍵字的差別教科
12/16 20:29, 10F

12/16 20:29, , 11F
書上都有寫= __ =
12/16 20:29, 11F
文章代碼(AID): #1D2Sey9L (C_and_CPP)
文章代碼(AID): #1D2Sey9L (C_and_CPP)