第六章模板
第六章 模 板
6.1模板的概念 C++是强类型语言,因此我们定义求最大值函数max()时,需要 对不同的数据类型分别定义不同的版本,例如: int maxint x, int y) i return(x>y)?x: y float max ( float x, float y) [return(x>y)?x: y;] double max double x, double y) ireturn(X>y)?x: y;] 这些函数版本执行的功能都是相同的,只是参数类型和返回类型不 同,能否为上述这些函数只写出一套代码?解决问题的一个方 法就是使用模板。所谓模板,就是写一个函数模子,用这个模子 套印出许多功能相同,参数类型和返回类型不同的函数。模板是 实现了真正的代码可重用性。 可以这么说:函数重载是指用同一个名字定义不同的函数,这些 函数功能不同,执行不同的操作。 函数模板是指用同一个名字定义不同的函数,这些函数功能相同, 而参数类型和返回类型不同
6.1 模板的概念 C++是强类型语言,因此我们定义求最大值函数max()时,需要 对不同的数据类型分别定义不同的版本,例如: int max(int x, int y) { return (x>y)?x : y;} float max(float x,float y) {return (x>y)?x : y;} double max(double x,double y) {return (x>y)?x : y;} 这些函数版本执行的功能都是相同的,只是参数类型和返回类型不 同, 能否为上述这些函数只写出一套代码?解决问题的一个方 法就是使用模板。所谓模板,就是写一个函数模子,用这个模子 套印出许多功能相同,参数类型和返回类型不同的函数。模板是 实现了真正的代码可重用性。 可以这么说: 函数重载是指用同一个名字定义不同的函数,这些 函数功能不同,执行不同的操作。 函数模板是指用同一个名字定义不同的函数,这些函数功能相同, 而参数类型和返回类型不同。 1
模板 模板分为函数模板(模子)和类模板(模子),允许用户分别用 它们构造(套印)出(模板)函数和(模板)类。 图显示了模板(函数模板和类模板),模板函数,模板类和对象 之间的关系。 模板 函数模板和类模板)模子 实例化 实例化 模板函 模板类 数 实例化 对象
模板 模板分为函数模板(模子)和类模板(模子),允许用户分别用 它们构造(套印)出(模板)函数和(模板)类。 图显示了模板(函数模板和类模板),模板函数,模板类和对象 之间的关系。 模 板 (函数模板和类模板) 模板函 数 模板类 对象 实例化 实例化 实例化 模子 2
6.2函数模板与模板函数 6.2.1函数模板的声明与模板函数的生成 函数模板的声明格式如下: template class type> 返回类型函数名(参数表) 函数体 其中 template是一个声明模板的关键字,它表示声明一个模板。 关键字 class表明后面的type是模板形参,在使用函数模板时, 必须将其实例化,即用实际的数据类型替代它。 例如,将求最大值函数max()定义成函数模板,如下所示: template<class T> T max(TX, Ty return (X>y)? X y;
6.2 函数模板与模板函数 6.2.1 函数模板的声明与模板函数的生成 函数模板的声明格式如下: template <class type> 返回类型 函数名(参数表) { 函数体 } 其中template是一个声明模板的关键字,它表示声明一个模板。 关键字class表明后面的type是模板形参,在使用函数模板时, 必须将其实例化,即用实际的数据类型替代它。 例如,将求最大值函数max () 定义成函数模板,如下所示: template<class T> T max(T x , T y) { return (x>y)? x:y; } 3
例6.1函数模板的程序 :f include<iostream. h> # include≤ string.h> 程序运行结果如下: template<class at> the max of i, i2 is: 56 AT max(AT X, AT y) the max of fl f2 is 24.5 i return(x>y)?x: y; y the max of dl. d2 is: 4656.346 void maino the max of cl c2 is a n i int il10, 12=56 float f=12.5,f2=24.5 double b1=50344d2=4656346; char cl=kc2=n cout<< the max of il, 2 is: "<<max(1, 12 <<endl cout<< the max of fl, f2 is: "<<max(f1, f2 <<end; cout<< the max of dl, d2 is: <<max d1, d2 <<endl; cout<” the max of clc2is:“<<max(c1,c2)<≤endl;
例6.1 函数模板的程序 # include<iostream.h> # include<string.h> template<class AT> AT max(AT x , AT y ) { return (x>y)? X : y; } void main() { int il=10, i2=56; float fl=12.5, f2=24.5; double b1=50.344,d2=4656.346; char c1=’k’,c2=’n’; cout<<”the max of il,i2 is: “<<max(i1,i2)<<endl; cout<<”the max of fl,f2 is: “<<max(f1,f2)<<endl; cout<<”the max of dl,d2 is: “<<max(d1,d2)<<endl; cout<<”the max of cl,c2 is: “<<max(c1,c2)<<endl; } 程序运行结果如下: the max of il,i2 is :56 the max of fl,f2 is :24.5 the max of dl,d2 is :4656.346 the max of cl,c2 is :n 4