[問題] 一個連結的小問題....

看板C_and_CPP (C/C++)作者 (狂風.怒浪)時間16年前 (2010/01/21 23:43), 編輯推噓0(005)
留言5則, 2人參與, 最新討論串1/1
我要問的問題是,如果以下的程式碼,用在同一個 main.cpp上, 而沒有把他分成 file2.cpp 和 ptt.h 檔的話 是可以執行的 但是 我把他用在同一個project1的話 他就出現 linker errer.... 我不知道為啥會這樣耶>_< 有沒有大大 幫我解惑一下 謝謝 ===============================錯誤訊息如下================================= [Linker error] undefined reference to `void ShowArray<int>(int*, int)' [Linker error] undefined reference to `void ShowArray<double>(double**, int)' ld returned 1 exit status C:\Documents and Settings\...\桌面\test\Makefile.win [Build Error] [project1.exe] Error 1 ==========================下面是三個檔案的程式碼 是使用dev-c++ compiler去編的 main.cpp ========================== #include <iostream> #include "ptt.h" using namespace std; int main(int argc, char *argv[]) { int thing[6]={13,31,103,301,310,130}; fuck sex[3]= { {"Ima Wolfe",2400.0}, {"ix fuckyo",1300.0}, {"pal gmd s",1800.0} }; double* pd[3]; for(int i=0;i<3;i++) pd[i]=&sex[i].amount; cout<<"template A start\n"; ShowArray(thing,6); cout<<"template B start\n"; ShowArray(pd,3); system("PAUSE"); return EXIT_SUCCESS; } ======================== file2.cpp ======================== #include <iostream> #include "ptt.h" using namespace std; template <typename T> void ShowArray(T arr[],int n) { cout<<"template A"<<endl; for(int i=0;i<n;i++) cout<<arr[i]<<" "; cout<<endl; } template <typename T> void ShowArray(T * arr[],int n) { cout<<"Template B"<<endl; for(int i=0;i<n;i++) cout<<*arr[i]<<" "; cout<<"\n"; } =========================== ptt.h =========================== #ifndef PTT_H_ #define PTT_H_ struct fuck { char name[50]; double amount; }; template <typename T> void ShowArray(T arr[], int n); template <typename T> void ShowArray(T * arr[], int n); #endif ============================ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.171.58.57

01/21 23:44, , 1F
通常 template 的函式實體也要一定寫在 header 檔裡面
01/21 23:44, 1F

01/21 23:46, , 2F
一併 orz
01/21 23:46, 2F

01/21 23:46, , 3F
所以說 如果把template放在另一個檔案 會產生error囉><
01/21 23:46, 3F

01/21 23:49, , 4F
http://0rz.tw/qlMFy <== google 查到的 你可以參考一下
01/21 23:49, 4F

01/21 23:54, , 5F
好的 謝謝j大 我等一下來看 他如何解說
01/21 23:54, 5F
文章代碼(AID): #1BM7OGzK (C_and_CPP)
文章代碼(AID): #1BM7OGzK (C_and_CPP)