分享

“模板”学习笔记(8)

 My镜像站 2011-12-26

一个模板中可以具有多个参数,即可以在一个模板中声明多个自定义的类型,如下面这句话:

template<class T1,class T2>

  而我们就可以利用这两个参数声明一个具有2种类型的成员。下面我用一个程序说下演示一下这个问题:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;
template<class T1,class T2>
class show
{
public:
    void show1(T1 &a){cout<<"show1:"<<a<<endl;}
    void show2(T2 &a){cout<<"show2:"<<a<<endl;}
};
 
int main()
{
    show<int,string> a;
    int temp1=5;
    string temp2="Hello,C++!";
    a.show1(temp1);
    a.show2(temp2);
    return 0;
}

  在上面的程序中,我在主函数中将两个类型T1和T2分别设置成了int型和string类型。这样一来,我们在程序的第15行和16行定义的整型变量和string型变量就可以在17行和18行被输出,结果如下:

另外一个需要注意的问题,我们也可以为模板参数提供默认的类型,比如说:

template<class T1,class T2=string>

  这样一来,我们就把T2参数默认设置成了string类型。那么在上面主程序中,我们把14行换成:

show<int> a;

  这样还是相当于:

show<int ,string> a;

  整个程序示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;
template<class T1,class T2=string>
class show
{
public:
    void show1(T1 &a){cout<<"show1:"<<a<<endl;}
    void show2(T2 &a){cout<<"show2:"<<a<<endl;}
};
 
int main()
{
    show<int> a;
    int temp1=5;
    string temp2="Hello,C++!";
    a.show1(temp1);
    a.show2(temp2);
    return 0;
}

  输出与上面一模一样,这里我就不把它粘上来了,^_^

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

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多