=================如何对模板进行重载====================
我们在运用一个函数模板的时候,很可能会增加这个函数的功能。比如说原先我们有一个交换函数:
void Swap(ElementType,ElementType);
它的功能就是对两个数进行交换。但是现在如果我们想对两个数组中的每一个数进行交换,那么就需要重载这个Swap函数,并且给它添加一个新的变量:int n。这个函数的作用就是循环数组中的每个元素,那么这个重载的Swap()函数就应该用如下方式进行声明:
void Swap(ElementType a[],ElementType b[],int n);
这样一来,women就对原有的Swap()函数进行了重载,即功能上的升级。下面是这个程序的例子:
#include <iostream>
using namespace std;
const int num=5;
//Swap函数的第一个版本
template<class ElementType>
void Swap(ElementType a,ElementType b)
{
ElementType temp;
cout<<"交换前,元素a和元素b的值为:"<<endl;
cout<<"a="<<a<<"\tb="<<b<<endl;a
cout<<"调用Swap(ElementType,ElementType)函数:"<<endl;
temp=b;
b=a;
a=temp;
cout<<"a="<<a<<"\tb="<<b<<endl;
}
//Swap函数的第二个版本
template<class ElementType>
void Swap(ElementType a[],ElementType b[],int n)
{
ElementType temp;
cout<<"交换前,数组a[]和数组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<<"调用Swap(ElementType,ElementType,int)函数:"<<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;
}
注意,在这个程序的第5行和18行我们都定义了一个模板类型ElementType。它用在紧接其后的模板函数的定义。这个程序主要完成额功能就是对两个数进行交换,同时对两个数组进行交换。下面就是这个程序的运行结果:
通过这个程序的运行结果,我们可以清楚的看到,利用模板重载这个概念,我们可以升级原有的函数,使之达到功能升级的地步~~