分享

“模板”学习笔记(2)

 My镜像站 2011-12-26

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

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

void Swap(ElementType,ElementType);

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

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

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

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函数的第一个版本
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。它用在紧接其后的模板函数的定义。这个程序主要完成额功能就是对两个数进行交换,同时对两个数组进行交换。下面就是这个程序的运行结果:

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多