C++类模板之小实例(1)

来源:互联网 发布:淘宝客服企业介绍范文 编辑:程序博客网 时间:2024/05/29 02:19

    模板是面向对象技术提高软件开发效率的重要手段,是C++语言的重要特征。函数模板可根据函数实参的类型,实例化成相应的具体函数,以处理不同类型的函数。

    类模板的定义有两种形式:

    类模板的成员函数既可以在类内声明类内实现,也可以在类内声明,在类外实现。注意两种不同的表达方式。

下面是一个完整实例

声明一个类模板,实现比较int型,float型和char型的两个变量的大小:

 

#include <iostream> using namespace std; template <class numtype>//定义类模板class Compare{   private :   numtype x,y;   public :   Compare(numtype a,numtype b)   {x=a;y=b;}   numtype max( )   {return (x>y)?x:y;}   numtype min( )   {return (x<y)?x:y;}  };int main( ){   Compare<int > cmp1(3,7);//定义对象cmp1,用于两个整数的比较   cout<<cmp1.max()<<"is the Maximum of two integer numbers ."<<endl;   cout<<cmp1.min( )<<"is the Minimum of two integer numbers."<<endl<<endl;   Compare<float > cmp2(45.78,93.6); //定义对象cmp2,用于两个浮点数的比较   cout<<cmp2.max( )<<"is the Maximum of two float numbers."<<endl;   cout<<cmp2.min( )<<"is the Minimum of two float numbers."<<endl<<endl;   Compare<char> cmp3('a','A'); //定义对象cmp3,用于两个字符的比较   cout<<cmp3.max( )<<"is the Maximum of two characters."<<endl;   cout<<cmp3.min( )<<"is the Minimum of two characters."<<endl;   return 0;} #include <iostream> using namespace std; template <class numtype>//定义类模板class Compare{   private :   numtype x,y;   public :   Compare(numtype a,numtype b)   {x=a;y=b;}   numtype max( );   numtype min( );}; template <class numtype>numtype Compare <numtype>:: max(){   {return (x>y)?x:y;}}template <class numtype>numtype Compare <numtype>:: min(){   {return (x<y)?x:y;}}int main( ){   Compare<int > cmp1(3,7);//定义对象cmp1,用于两个整数的比较   cout<<cmp1.max()<<"is the Maximum of two integer numbers ."<<endl;   cout<<cmp1.min( )<<"is the Minimum of two integer numbers."<<endl<<endl;   Compare<float > cmp2(45.78,93.6); //定义对象cmp2,用于两个浮点数的比较   cout<<cmp2.max( )<<"is the Maximum of two float numbers."<<endl;   cout<<cmp2.min( )<<"is the Minimum of two float numbers."<<endl<<endl;   Compare<char> cmp3('a','A'); //定义对象cmp3,用于两个字符的比较   cout<<cmp3.max( )<<"is the Maximum of two characters."<<endl;   cout<<cmp3.min( )<<"is the Minimum of two characters."<<endl;   return 0;}