第二节函数模板(教材①P316327) 、函数模板的定义 template <class t1, class T2,...> 返回类型函数名(形参表) 函数体 其中: template< class t1, class t2…>为模板函数的声 明 class t1 class t2,为模板形参T1、T2为虚拟 类型参数。 >可把模板形参改为: typename T1, typename T2
第二节 函数模板(教材①P316-327) 一、函数模板的定义 template<class T1,class T2,… > 返回类型 函数名(形参表) { 函数体 } 其中: ➢template<class T1,class T2,… >为模板函数的声 明 ➢ class T1,class T2,…为模板形参——T1、T2为虚拟 类型参数。 ➢可把模板形参改为:typename T1,typename T2,…
第二节函数模板(教材①P316327) 例【62】定义一个函数模板swap(),使之能实现二个 整数的交换、二个双精度数的交换、二个点( point 类)的交换。( point类的定义在 hhpoint h中) #includesiostream.h> #include hhpoint h ∥ template< typename T>∥模板函数声明 template< class①>∥模板函数声明 void swap(t &a,T&b) fT temp temp=a; a=b; b=temp;
第二节 函数模板(教材①P316-327) 例【6.2】定义一个函数模板swap( ),使之能实现二个 整数的交换、二个双精度数的交换、二个点(point 类)的交换。(point类的定义在hhpoint.h中) #include<iostream.h> #include"hhpoint.h" //template <typename T> //模板函数声明 template <class T> //模板函数声明 void swap(T &a,T &b) { T temp; temp=a;a=b;b=temp; }
第二节函数模板(教材①P316327) s void main(void) {inti=20j=30; double x=80.5, y=92.6; point pl(40,50),p2(70,80); swap(i,);/将模板函数实例化为整型数据交换 cout<<ni=<<i<<i=w<<i<<endl swap(x,y);/将模板函数实例化为双精度型数据交换 cout<< nx=<<x<<y=<<y<<endl swap(pn2)/将模板函数实例化为 point类的数据交换 cout<<inpl: pl printo; cout<<\np2: ";p2 printo;
第二节 函数模板(教材①P316-327) void main(void) { int i=20,j=30; double x=80.5,y=92.6; point p1(40,50),p2(70,80); swap(i,j);//将模板函数实例化为整型数据交换 cout<<"\ni="<<i<<" j="<<j<<endl; swap(x,y);//将模板函数实例化为双精度型数据交换 cout<<"\nx="<<x<<" y="<<y<<endl; swap(p1,p2);//将模板函数实例化为point类的数据交换 cout<<"\np1:";p1.print(); cout<<"\np2:";p2.print(); }