[問題] 參數化型別

看板C_and_CPP (C/C++)作者 (行人)時間13年前 (2012/10/03 11:30), 編輯推噓4(406)
留言10則, 6人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC 6.0 問題(Question): 自己實作一個Array,錯誤碼如下: error LNK2001: unresolved external symbol "public: __thiscall Array<int>::Array<int>(int)" (??0?$Array@H@@QAE@H@Z) 程式碼(Code):(請善用置底文網頁, 記得排版) /* main.cpp */ #include "stdafx.h" #include "Array.h" #include <iostream> using std::cout; int main(int argc, char* argv[]) { Array<int> tmp; return 0; } ------------------------------------------------- /* Array.h */ const int DefaultSize = 10; template<class T> class Array { public: //Constructor Array(int itsSize = DefaultSize); Array(const Array &rhs); virtual ~Array(){ delete [] pType; } //Operator Array& operator=(const Array &rhs); T& operator[](int offset) const { return pType[offset]; } //Interface int GetSize() const; private: T* pType; int itsSize; }; ------------------------------------------------- /* Array.cpp */ #include "stdafx.h" #include "Array.h" template<class T> Array<T>::Array(int Size = DefaultSize):itsSize(Size) { pType = new T[Size]; for (int i=0 ; i<Size ; i++) pType[i]=0; } template<class T> Array<T>::Array( const Array &rhs ) { itsSize = rhs.GetSize(); pType = new T[Size]; for (int i=0 ; i<Size ; i++) pType[i]=rhs[i]; } template<class T> Array<T>& Array<T>::operator=( const Array &rhs ) { if (this == &rhs) return *this; delete [] pType; itsSize = rhs.GetSize(); pType = new T[Size]; for (int i=0 ; i<Size ; i++) pType[i]=rhs[i]; return *this; } template<class T> int Array<T>::GetSize() const { return itsSize; } 補充說明(Supplement): 基本上是照著書上範例打的, 唯一的差異是書上把所有東西都寫在同一份.h, 但怎麼試都compile不過... 想請問錯在哪? 謝謝~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.34.227.117

10/03 11:49, , 1F
你要把template的實作內容寫在.h裡面,而不是.cpp
10/03 11:49, 1F

10/03 12:00, , 2F
過了耶謝謝,可以請問為什麼非得要這樣嗎...@@" 是牽涉到
10/03 12:00, 2F

10/03 12:00, , 3F
compiler的什麼細節?
10/03 12:00, 3F

10/03 12:25, , 4F
http://0rz.tw/jgBsT 這邊有人說到~
10/03 12:25, 4F

10/03 13:45, , 5F
喔喔~ 謝謝!
10/03 13:45, 5F

10/03 15:00, , 6F
如果也在.cpp里,要編成lib 之後再去連結
10/03 15:00, 6F

10/03 15:08, , 7F
不是沒編成lib的問題,想想看template的原理吧
10/03 15:08, 7F

10/03 16:19, , 8F
連結裡面提到的問題好有趣..怎麼將 template 資訊隱藏
10/03 16:19, 8F

10/03 19:02, , 9F
硬要寫在cpp的話 可以針對每種case做specialization
10/03 19:02, 9F

10/03 19:04, , 10F
但是遇到沒定義到的會有link error
10/03 19:04, 10F
文章代碼(AID): #1GQx5W03 (C_and_CPP)
文章代碼(AID): #1GQx5W03 (C_and_CPP)