=================如何對(duì)模板進(jìn)行重載====================
我們?cè)谶\(yùn)用一個(gè)函數(shù)模板的時(shí)候,很可能會(huì)增加這個(gè)函數(shù)的功能。比如說原先我們有一個(gè)交換函數(shù):
void Swap(ElementType,ElementType); |
它的功能就是對(duì)兩個(gè)數(shù)進(jìn)行交換。但是現(xiàn)在如果我們想對(duì)兩個(gè)數(shù)組中的每一個(gè)數(shù)進(jìn)行交換,那么就需要重載這個(gè)Swap函數(shù),并且給它添加一個(gè)新的變量:int n。這個(gè)函數(shù)的作用就是循環(huán)數(shù)組中的每個(gè)元素,那么這個(gè)重載的Swap()函數(shù)就應(yīng)該用如下方式進(jìn)行聲明:
void Swap(ElementType a[],ElementType b[], int n); |
這樣一來,women就對(duì)原有的Swap()函數(shù)進(jìn)行了重載,即功能上的升級(jí)。下面是這個(gè)程序的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | #include <iostream> using namespace std; const int num=5; //Swap函數(shù)的第一個(gè)版本 template < class ElementType> void Swap(ElementType a,ElementType b) { ElementType temp; cout<< "交換前,元素a和元素b的值為:" <<endl; cout<< "a=" <<a<< "\tb=" <<b<<endl;a cout<< "調(diào)用Swap(ElementType,ElementType)函數(shù):" <<endl; temp=b; b=a; a=temp; cout<< "a=" <<a<< "\tb=" <<b<<endl; } //Swap函數(shù)的第二個(gè)版本 template < class ElementType> void Swap(ElementType a[],ElementType b[], int n) { ElementType temp; cout<< "交換前,數(shù)組a[]和數(shù)組b[]的值為:" <<endl; for ( int i=0;i<n;i++) { cout<< "a[" <<i<< "]為:" <<a[i]<< " " ; } cout<<endl; for ( int i=0;i<n;i++) { cout<< "b[" <<i<< "]為:" <<b[i]<< " " ; } cout<<endl; cout<< "調(diào)用Swap(ElementType,ElementType,int)函數(shù):" <<endl; for ( int i=0;i<n;i++) { temp=b[i]; b[i]=a[i]; a[i]=temp; } for ( int i=0;i<n;i++) { cout<< "a[" <<i<< "]為:" <<a[i]<< " " ; } cout<<endl; for ( int i=0;i<n;i++) { cout<< "b[" <<i<< "]為:" <<b[i]<< " " ; } cout<<endl; } int main() { int x=1,y=2; Swap(x,y); int num1[num]={1,2,3,4,5}; int num2[num]={6,7,8,9,10}; Swap(num1,num2,num); return 0; } |
注意,在這個(gè)程序的第5行和18行我們都定義了一個(gè)模板類型ElementType。它用在緊接其后的模板函數(shù)的定義。這個(gè)程序主要完成額功能就是對(duì)兩個(gè)數(shù)進(jìn)行交換,同時(shí)對(duì)兩個(gè)數(shù)組進(jìn)行交換。下面就是這個(gè)程序的運(yùn)行結(jié)果:
通過這個(gè)程序的運(yùn)行結(jié)果,我們可以清楚的看到,利用模板重載這個(gè)概念,我們可以升級(jí)原有的函數(shù),使之達(dá)到功能升級(jí)的地步~~
聯(lián)系客服