s7edge高仿和正品差别:“模板”学习笔记(2)

来源:百度文库 编辑:中财网 时间:2024/05/02 06:27:26

=================如何对模板进行重载====================

      我们在运用一个函数模板的时候,很可能会增加这个函数的功能。比如说原先我们有一个交换函数:

void Swap(ElementType,ElementType);

  它的功能就是对两个数进行交换。但是现在如果我们想对两个数组中的每一个数进行交换,那么就需要重载这个Swap函数,并且给它添加一个新的变量:int n。这个函数的作用就是循环数组中的每个元素,那么这个重载的Swap()函数就应该用如下方式进行声明:

void Swap(ElementType a[],ElementType b[],int n);

  这样一来,women就对原有的Swap()函数进行了重载,即功能上的升级。下面是这个程序的例子:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263#include using namespace std;const int num=5;//Swap函数的第一个版本template<class ElementType>void Swap(ElementType a,ElementType b){    ElementType temp;    cout<<"交换前,元素a和元素b的值为:"<    cout<<"a="<"\tb="<    cout<<"调用Swap(ElementType,ElementType)函数:"<    temp=b;    b=a;    a=temp;    cout<<"a="<"\tb="<}//Swap函数的第二个版本template<class ElementType>void Swap(ElementType a[],ElementType b[],int n){    ElementType temp;    cout<<"交换前,数组a[]和数组b[]的值为:"<    for(int i=0;i    {        cout<<"a["<"]为:"<" ";     }    cout<    for(int i=0;i    {        cout<<"b["<"]为:"<" ";     }    cout<    cout<<"调用Swap(ElementType,ElementType,int)函数:"<    for(int i=0;i    {        temp=b[i];        b[i]=a[i];        a[i]=temp;    }    for(int i=0;i    {        cout<<"a["<"]为:"<" ";     }    cout<    for(int i=0;i    {        cout<<"b["<"]为:"<" ";     }    cout<}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。它用在紧接其后的模板函数的定义。这个程序主要完成额功能就是对两个数进行交换,同时对两个数组进行交换。下面就是这个程序的运行结果:

      通过这个程序的运行结果,我们可以清楚的看到,利用模板重载这个概念,我们可以升级原有的函数,使之达到功能升级的地步~~