【正文】
謂的頭文件原則: “ 在頭文件中,不要放置分配存儲(chǔ)空間的任何東西 ” ,為了防止在連接期間的多重定義錯(cuò)誤。 // 棧底 T *p。 void push(T a)。 文件: 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 26 template class T StackT::Stack(int s){ v=p=new T[sz=s]。} template class T int StackT:: size() const { return pv。 // 連接錯(cuò)誤 } 文件 : error LNK2020: unresolved external symbol public: int __thiscall Stackint::push(int) (?push?$stackHQAEHXZ) 發(fā)生連接錯(cuò)誤: 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 28 From MSDN: ? Linker Tools Error LNK2020 ? unresolved external symbol symbol ? Code will generate this error message if it references something (like a function, variable, or label) that the linker can’t find in all the libraries and object files it searches. In general, there are two reasons this error occurs: what the code asks for doesn’t exist (the symbol is spelled incorrectly or uses the wrong case, for example), or the code asks for the wrong thing (you are using mixed versions of the libraries?some from one version of the product, others from another version). ? Numerous kinds of coding and build errors can cause LNK2020. Several specific causes are listed below, and some have links to more detailed explanations. …… 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 29 模板中的常量 模板參數(shù)并不局限于類定義的類型,可以使用編譯器內(nèi)置類型。 // 在實(shí)例化時(shí),設(shè)置 Array類的長度 public: Tamp。 return array[index]。 public: Number(float ff = ) : f(ff) {} Numberamp。 } operator float() const { return f。 x) { return os 。 operator[](int i) { require(0 = i amp。 return npoperator[ ](i)。 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 33 int main() { HolderNumber h。 for(int j = 0。 class Base { int i。 template class T class derived:public Base{ 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 36 T t。 () 。 public: void g() { cout “g” endl。 // … }。 // ()。 } 這里 T可以是 int, char ,float, 或者任何重載了 算符的對象。 char c, d。 // 調(diào)用 max(char c,char d)。 for (int i=0。 } template class T T sum(T *array, T *array2, int size) { T total。 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 47 return total。 // double dtotal = sum(douarr, 10)。 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 49 1. 請實(shí)現(xiàn)一個(gè)隊(duì)列模版 Queueclass T 作業(yè) :