【正文】
// double dtotal = sum(douarr, 10)。 } template class T T sum(T *array, T *array2, int size) { T total。 // 調(diào)用 max(char c,char d)。 } 這里 T可以是 int, char ,float, 或者任何重載了 算符的對(duì)象。 // … }。 () 。 class Base { int i。 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國(guó)科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 33 int main() { HolderNumber h。 operator[](int i) { require(0 = i amp。 } operator float() const { return f。 return array[index]。 // 連接錯(cuò)誤 } 文件 : error LNK2020: unresolved external symbol public: int __thiscall Stackint::push(int) (?push?$stackHQAEHXZ) 發(fā)生連接錯(cuò)誤: 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國(guó)科學(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ì)》 中國(guó)科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 29 模板中的常量 模板參數(shù)并不局限于類定義的類型,可以使用編譯器內(nèi)置類型。 文件: 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國(guó)科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 26 template class T StackT::Stack(int s){ v=p=new T[sz=s]。 // 棧底 T *p。 template class T T StackT:: pop() { return * p 。 ~Stack() 。 i){ if(()!=i) { error() 。 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國(guó)科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 19 for (i= 0。} ~Stack() { delete[ ] v。 // 實(shí)例化成 char 型棧類; 注意:類模板實(shí)例化后的結(jié)果是類,而不是對(duì)象! 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國(guó)科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 16 類對(duì)象生成 ? 類模板實(shí)例化得到的類可以進(jìn)行實(shí)例化,生成最 終的對(duì)象。} ~Stack() { delete[ ] v。 2. 由于 T是全局名,無(wú)法重新 定義,一個(gè)類不能同時(shí)用到 char棧和 int棧; 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國(guó)科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 10 smalltak方法 (略 ) 使用繼承 ? 復(fù)雜 ,混亂 ! 《面向?qū)ο蟪绦蛟O(shè)計(jì)》 中國(guó)科學(xué)技術(shù)大學(xué)計(jì)算機(jī)系 馬建輝 11 C++的方法:模板 改進(jìn) typedef,將它從預(yù)處理器移入到編譯器中。 // 棧頂 int sz。} int size() const { return pv。因此應(yīng)該可以重用 IntStack的代碼。 // 棧的大小 public: IntSta