模版-----是為了讓**更加通用,使**不受資料型別的影響。減少**冗餘。模版將資料型別當作乙個引數進行傳遞。包括函式模版和類模板。
函式模版:
//定義乙個比較大小的函式模版
template//
也可以寫成 template
type max(type a,type b)
intmain()
模版會根據傳遞的實參自動進行資料型別的推演,比如在max(2.5,2.3)中,模版會根據2.5是double,2.3是double,模版會推導出type是double型別,生成乙個模版函式,使用double型別的比較函式。所以模版雖然方便,但是效率不高。
比如,呼叫函式max(1,2)時,編譯器會先根據函式模版生成乙個int型別的模版函式,然後在呼叫這個函式。
//模版函式int max(int a, int
b)
當出現實參型別不一致時,普通函式正常執行,模版會出現錯誤,如:
/*template//會產生二義性
type max(type a,type b)
*/int max(int a,int
b) //會自動進行隱式轉換
intmain()
也可以重新編寫模版函式,如:
templatetype2 max(type1 a,type2 b)
如果是類物件進行比較,需要過載比較運算子。模版只負責比較,不管如何進行比較。
classtest
bool
operator>(const test &t)
};template
type1 max(type1 a,type1 b)
intmain()
類模板:
利用類模板簡單實現線性鍊錶。
int a = int(); //將a初始化為0;
模版類成員函式都是模版函式,不允許將類定義和實現分離
#include usingnamespace
std;
//宣告list類
template
class
list;
template
class
listnode
//零初始化:根據不同型別進行初始化。如,int a = int() //a被初始化為0。
listnode(type d,listnode
*n =null):data(d),next(n){}
~listnode(){}
};template
class
list
}};template
//模版類的成員函式都是模版函式,所以必須寫templatelist
::list() //限定是list::
template
list
::~list()
}template
bool list::push_back(type x)
intmain()
mylist.show_list();
return0;
}
c 模版筆記
一 一般模板函式形式 include using namespace std templae 若有多個參引數可如此定義即可 template 定義不定型別 const type mymax const type valueone,const type valuetow int main 上述 在編譯...
C 筆記(類模版)
模版類中有模版函式偏特化,有模版泛化,全特化,過載 模版函式呼叫優先順序 全特化,特化,泛化 泛化 template struct tc void functest1 static int m stc 宣告乙個靜態成員變數 template int tc m stc 50 定義靜態成員變數,偏特化 ...
C 筆記 04C 模版1
include using namespace std oop三大特徵 封裝 繼承 多型 第二部分 模版 c templates 1.函式模版 2.類模板 需要搞清楚的知識點 函式模版 模版的例項化,顯示,隱式 模版函式 模版的實參推演 模版型別引數 模版的非型別引數 模版的特例化 專用化 模版函式...