[問題] template class編譯問題

看板C_and_CPP (C/C++)作者 (Rebellionyu)時間9年前 (2017/02/19 21:38), 編輯推噓1(103)
留言4則, 3人參與, 最新討論串1/1
開發平台(Platform): Windows 10 編譯器:MinGW G++ 額外使用到的函數庫(Library Used): No 問題(Question): 我在練習data structure linked list,目前有四個檔案,分別是: SLinkedList.h, SLinkedList.cpp, SNode.h, main.cpp code在底下。 餵入的資料(Input): compile command:g++ main.cpp SLinkedList.cpp 預期的正確結果(Expected Output): 正確編譯產生a.exe檔 錯誤結果(Wrong Output): ...\AppData\Local\Temp\cceyYWGl.o:main.cpp:(.text+0x16): undefined reference to `SLinkedList<std::string>::SLinkedList()' ...\AppData\Local\Temp\cceyYWGl.o:main.cpp:(.text+0x26): undefined reference to `SLinkedList<std::string>::~SLinkedList()' collect2.exe: error: ld returned 1 exit status 程式碼(Code):(請善用置底文網頁, 記得排版) ================================ SLinkedList.h ================================ #include "SNode.h" #ifndef SLINKEDLIST_H #define SLINKEDLIST_H template<typename E> class SLinkedList { public: SLinkedList(); ~SLinkedList(); bool empty() const; const E& front() const; void addFront(const E& e); void removeFront(); private: SNode<E>* head; }; #endif ================================ SLinkedList.cpp ================================ #include "SLinkedList.h" #include <stddef.h> template<typename E> SLinkedList<E>::SLinkedList() : head(NULL) { } template<typename E> SLinkedList<E>::~SLinkedList() { while (!empty()) removeFront(); } template<typename E> bool SLinkedList<E>::empty() const { return head == NULL; } template<typename E> const E& SLinkedList<E>::front() const { return head->elem; } template<typename E> void SLinkedList<E>::addFront(const E& e) { SNode<E>* v = new SNode<E>; v->elem = e; v->next = head; head = v; } template<typename E> void SLinkedList<E>::removeFront() { SNode<E>* old = head; head = old->next; delete old; } ================================ SNode.h ================================ #ifndef SNODE_H #define SNODE_H template<typename E> class SLinkedlist; template <typename E> class SNode { private: E elem; SNode<E>* next; friend class SLinkedlist<E>; }; #endif ================================ main.cpp ================================ #include "SLinkedList.h" #include <iostream> using namespace std; int main() { SLinkedList<string> b; return 0; } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.48.28 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1487511534.A.826.html

02/19 21:45, , 1F
看一下本版的#1Nu-yT4R 應該是一樣的問題
02/19 21:45, 1F

02/19 21:46, , 2F
我記得沒錯tempalte盡量不要拆 h跟cpp 雖然說還是可以拆
02/19 21:46, 2F

02/19 21:46, , 3F
但是有些小技巧
02/19 21:46, 3F

02/19 21:56, , 4F
好,謝謝,我來試試
02/19 21:56, 4F
文章代碼(AID): #1OgP_kWc (C_and_CPP)
文章代碼(AID): #1OgP_kWc (C_and_CPP)