在理发店坑了报警有么:“模板”学习笔记(8)

来源:百度文库 编辑:偶看新闻 时间:2024/05/05 11:06:44

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

template<class T1,class T2>

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

1234567891011121314151617181920#include #include using namespace std;template<class T1,class T2>class show{public:    void show1(T1 &a){cout<<"show1:"<    void show2(T2 &a){cout<<"show2:"<}; 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;

  整个程序示例如下:

1234567891011121314151617181920#include #include using namespace std;template<class T1,class T2=string>class show{public:    void show1(T1 &a){cout<<"show1:"<    void show2(T2 &a){cout<<"show2:"<}; int main(){    show<int> a;    int temp1=5;    string temp2="Hello,C++!";    a.show1(temp1);    a.show2(temp2);    return 0;}

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