提出問題
1)某些類,出元素類型不同,其他完全相同,如何做可以多快好省地定義出一批類?
解決方法_類模板
1)在定義類時,加上一個或多個類型參數,在使用類模板時指定類型參數的具體參數類型,編譯器即可自動生成模板類
類的寫法:
template<class 參數類型1,class 參數類型2, ...>
class 類模板名{
成員函數和成員變量
};
類成員函數的寫法
template<class 參數類型1,class 參數類型2, ...> //類型參數表
返回值類型 類模板名<類型參數名列表>::函數名(參數表)
{
......
}
定義對象的寫法
類模板名<真實類型表> 對象名(構造函數實參表);
2)示例:pair類模板
template<class t1,class t2> //定義類模板
class Pair{ //類模板名
public:
t1 key;
t2 vau;
Pair(t1 k, t2 v) :key(k), vau(v){ }
bool operator<(const Pair<t1, t2>& p);
};
template<class t1,class t2> //成員函數 operator<
bool Pair<t1, t2>::operator<(const Pair<t1, t2>& p){
return key < p.key;
}
int main(){
Pair<double, int> t1(1,2);
Pair<double, int> t2(2,3);
if (t1 < t2)
cout << "right" << endl;
Pair<string, int> p3("Tom", 9);
cout<< p3.key << " " << p3.vau << endl;
return 0;
}
輸出:
right
Tom 9
3)函數模板也可以作爲類模板成員
例如:
template<class t1,class t2>
class air{
public:
template<class t3>
void func(t3 c){
cout << c << endl;
}
};
int main(){
air<int, double> q; //定義對象
q.func('c'); //調用成員函數 根據參數類型進行函數模板實例化
q.func("Tom");
q.func(4);
return 0;
}
輸出:
c
Tom
4
4)類模板的類型參數表中可以出現非類型參數
例如:
template<class t1,int size> //int 類型的 size 不是類型參數 用來標誌成員數組元素的個數
class air{
public:
t1 a[size];
};
int main(){
air<int, 10> p1; //size 賦值爲10
for (int i = 0; i < 10; ++i)
p1.a[i] = i;
for (int i = 0; i < 10; ++i)
cout << p1.a[i] << " ";
return 0;
}
輸出:
0 1 2 3 4 5 6 7 8 9