[問題] Undefined Reference to class template

看板C_and_CPP (C/C++)作者 (Bor)時間13年前 (2013/01/04 00:04), 編輯推噓2(208)
留言10則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Solaris, g++ 4.4.2 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) N/A 問題(Question): Undefined reference 餵入的資料(Input): 5 C++ files command: g++ main.cpp Queue.h Queue.cpp Except.h Except.cpp 預期的正確結果(Expected Output): N/A 錯誤結果(Wrong Output): Undefined first referenced symbol in file Queue<int>::Queue() /var/tmp//cc2RiLhE.o 程式碼(Code):(請善用置底文網頁, 記得排版) main.cpp: #include "Queue.h" int main(int argc, char **argv) { Queue<int> *IQueue = new Queue<int>; return 0; } Queue.h: #ifndef QUEUE_H #define QUEUE_H #include "Except.h" template<typename node_Type> struct node { node<node_Type> *next; node_Type data; }; template<typename Type> class Queue { public: Queue(); private: node<Type> *head; node<Type> *tail; Except handler; }; #endif // QUEUE_H Queue.cpp: #include "Queue.h" #ifndef NULL #define NULL 0 #endif template<typename Type> Queue<Type>::Queue() : handler( "Attempt to dequeue empty queue" ) { //ctor head = tail = NULL; } Except.h: #ifndef _EXCEPT_H #define _EXCEPT_H class Except { public: Except(char *str); operator const char*() const {return error;} private: char *error; }; Except.cpp: #include <iostream> #include <string.h> #include "Except.h" Except::Except(char *str) { error=strdup(str); } 補充說明(Supplement): Queue.cpp和Queue.h的部份還有很多個一樣的錯誤 (只要在main.cpp裡一用到Queue.h裡的函式時就會出現Undefined Reference, 在此為了版面簡潔所以就只留下constructor的部份了) 請問是什麼地方出了問題呢? 先謝謝大家的回答了 -- Someday, so I believe. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 1.171.111.52 ※ 編輯: dibery 來自: 1.171.111.52 (01/04 00:05)

01/04 00:07, , 1F
Queue<Type>::Queue() 的實做別跟宣告拆開
01/04 00:07, 1F

01/04 00:07, , 2F
全部寫在 .h 檔就好
01/04 00:07, 2F

01/04 00:08, , 3F
template要在header file裡定義
01/04 00:08, 3F

01/04 00:12, , 4F
一定沒辦法拆開嗎?因為作業要求要寫成.h和.cpp檔...
01/04 00:12, 4F

01/04 00:12, , 5F
因為我也有發現寫在H裡面可以用,但是這樣CPP就空掉了...
01/04 00:12, 5F

01/04 00:27, , 6F
目前大部份的compiler都不支援template分離實作
01/04 00:27, 6F

01/04 00:27, , 7F
如果堅持要有一個 .cpp 的話,你可以把 main.cpp 裡面的
01/04 00:27, 7F

01/04 00:27, , 8F
一定要用.cpp的話,就放棄template吧
01/04 00:27, 8F

01/04 00:28, , 9F
#include "Queue.h" 改成 #include "Queue.cpp"
01/04 00:28, 9F

01/05 10:25, , 10F
謝謝,已經可以用了:)
01/05 10:25, 10F
文章代碼(AID): #1GvQltRF (C_and_CPP)
文章代碼(AID): #1GvQltRF (C_and_CPP)