模板类

#include "iostream"

#if 0 //不同类型的参数 作交换函数
void swap(int &a,int &b)
{
int c ;
c = a;
a = b;
b = c;
}
void swap2(float &a, float &b)
{
float c;
c = a;
a = b;
b = c;
}

void main1()
{
int a = 1 ,b = 2;
swap(a,b);
printf("\na = %d, b = %d \n",a,b);

float a1 = 1.1 , b1 = 2.1;
swap2(a1,b1);
printf("\na1 = %f, b1 = %f \n",a1,b1);

system("pause");
}
#endif

#if 1 //通过模板来写上述函数,就比较简便

template <typename T>

void swap(T &a, T &b)
{
T c ;
c = a;
a = b;
b = c;
}

void main()
{
int a = 1, b = 2;
swap(a,b);
printf("\na = %d b = %d\n",a,b);

float a1 = 1.1 ,b1 = 2.2;
swap<float>(a1,b1);
printf("\na1 = %f b1 = %f\n",a1,b1);
system("pause");
}
#endif

心得: 通过模板类可以简化重复写工作,如上述程序交换函数,只是带的类型参数不一样,而要重写一遍,这样浪费时间而且程序可读性变差。通过模板类之后,简化上述操作。

 

template <typename T>   // template 是关键字  typename 告诉编译器,T为类型,不用报错。

 

posted @ 2015-08-19 23:05  潘探  阅读(554)  评论(0)    收藏  举报