[問題] template實作問題

看板C_and_CPP作者 (單純的美好)時間13年前 (2010/11/09 21:30), 編輯推噓0(0012)
留言12則, 2人參與, 最新討論串1/1
( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 ) ( 未必需要依照此格式,文章條理清楚即可 ) 遇到的問題: (題意請描述清楚) 看C++ primer 4/e中寫說,要在編譯期讓compiler看到template class的定義才能實體化 而書中寫出兩種編譯模式 (p. 644) 我嘗試使用第一種置入式的,結果一直說我重複定義... 另外,第二種分離式的好像沒支援? 希望得到的正確結果: 編譯成功,可以跑 程式跑出來的錯誤結果: 我在linux上,用 g++ -o template.cpp ta.cpp ta.cpp:4: error: redefinition of ‘const int A<T, N>::a’ ta.h:6: error: ‘const int a’ previously declared here ta.cpp:5: error: redefinition of ‘void A<T, N>::print(T (&)[N])’ ta.cpp:5: error: ‘void A<T, N>::print(T (&)[N])’ previously declared here 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) linux, g++ 有問題的code: (請善用置底文標色功能) ta.h http://codepad.org/nFtPiBOD ta.cpp http://codepad.org/p0R54fe6 template.cpp http://codepad.org/epIdYZ7A 補充說明: 後來我將ta.h中的 #include "ta.cpp" 移除掉 並將template.cpp中 #include "ta.h" 改成 #include "ta.cpp" 卻可以正常執行了 但是跟書上不太一樣 = = -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.113.208.235

11/09 21:45, , 1F
科科...你有看到 utilities.cc 裡面 include 什麼標頭
11/09 21:45, 1F

11/09 21:46, , 2F
檔嗎? #include "ta.cpp" 其實就是把 ta.cpp 的內容
11/09 21:46, 2F

11/09 21:46, , 3F
複製貼上在 ta.h 裡, 如果這時候 ta.cpp 再 include
11/09 21:46, 3F

11/09 21:48, , 4F
一次, 那他的內容就重複兩次了, 所以才會有錯. export
11/09 21:48, 4F

11/09 21:48, , 5F
的話, 應該只要知道他的概念就好, 未來應該會被拿掉
11/09 21:48, 5F

11/09 22:00, , 6F
挖勒...被騙了 ㄏㄏ 謝啦
11/09 22:00, 6F

11/09 22:06, , 7F
話說我把#include"ta.h"從ta.cpp中拿掉卻出現
11/09 22:06, 7F

11/09 22:07, , 8F
ta.cpp:3: error: expected initializer before ‘<’ t
11/09 22:07, 8F

11/09 22:08, , 9F
ta.cpp : 4 也是一樣狀況..
11/09 22:08, 9F

11/09 22:09, , 10F
你只要 template.cpp 有編過就表示 ta.cpp 沒問題, 它
11/09 22:09, 10F

11/09 22:09, , 11F
只是複製用的檔案, 不要拿他來編譯
11/09 22:09, 11F

11/09 22:11, , 12F
嗯嗯,ok了 感謝^^
11/09 22:11, 12F
文章代碼(AID): #1CsKpq8P (C_and_CPP)