C++类模板template

 /*类模板:
对于功能相同而数据类型不同的一些函数,可以定义一个可对任何类型变量进行操作的函数模板,
在调用函数时,系统会根据实参的类型,取代函数模板中的类型参数,得到具体的函数*/  
 
#include<iostream>
using namespace std;
template <class numtype>
class Compare
{public:
    Compare(numtype a,numtype b)
    {x=a,y=b;}
    numtype max()
    {return (x>y)? x:y;}
         numtype min()
        {return (x<y)? x:y;}  //类内定义函数  
private:
    numtype x,y;
};
int main()
{

  Compare<int> cmp1(3,7); //定义对象cmp1,用于两个整数的比较
  cout<<cmp1.max()<<" is the maximum of the two integer numbers"<<endl;
  Compare<float> cmp2(4.6,9.944);
  cout<<cmp2.max()<<" is the maximum of the two float numbers"<<endl;
  Compare<char> cmp3('f','g');//定义对象cmp1,用于两个字符的比较
  cout<<cmp3.max()<<" is the maximum of the two char numbers"<<endl;
  Compare<char> *cchar = new Compare<char>('a','A');//能用指针形式动态创建  
  cout<<"字符"<<cchar->max()<<"大于"<<"字符"<<cchar->min()<<endl;  
}

注:template意思是“模板”,是申明类模板时必须写的关键字,template后面的尖括号的内容为类模板的参数列表,关键字class表示其后的是类型参数,在本例中numtype就是一个类型参数名,可以任意取,这里表示“数据类型:的意思而已。numtype是一个虚拟类型参数名,在以后被一个实际的类型名取代。如int float char ,可以一类多用。

由于类模板包含类型参数,因此又层称为参数化的类

如果是类是对象的抽象,对象是类的实例。那么类模板是类的抽象,类是类模板的实例

利用类模板可以建立含各种数据类型的类

那么,上面例子怎么改写成类外定义呢??如下把max 类外定义

#include<iostream>
using namespace std;
template<class numtype>     //定义类模板
class Compare
{
public:
    Compare(numtype a,numtype b)
    {x=a,y=b;}
    numtype max();
        numtype min()
        {return (x<y)? x:y;}  //类内定义函数  

private:
    numtype x,y;
};

template<class numtype>   //必须要加这一行,申明类模板,末尾无分号
numtype Compare<numtype>::max() //类外定义成员函数,numtype虚拟类型名,Compare<numtype>是个整体,带参的类,max在其作用域类
  {return (x>y)? x:y;}



int main()
{
  Compare<int> cmp1(3,7); //定义对象cmp1,用于两个整数的比较
  cout<<cmp1.max()<<" is the maximum of the two integer numbers"<<endl;
  Compare<float> cmp2(4.6,9.944);
  cout<<cmp2.max()<<" is the maximum of the two float numbers"<<endl;
  Compare<char> cmp3('f','g');//定义对象cmp1,用于两个字符的比较
  cout<<cmp3.max()<<" is the maximum of the two char numbers"<<endl;
  Compare<char> *cchar = new Compare<char>('a','A');//能用指针形式动态创建  
  cout<<"字符"<<cchar->max()<<"大于"<<"字符"<<cchar->min()<<endl;  

}

注:(1)在类申明前加入一行,格式为

   template<class 虚拟类型参数》

如:

template<class numtype>     //定义类模板末尾无分号
class Compare
{...};     //类体

(2)类模板定义对象时用以下形式:

  类模板 <实际类型名> 对象名;

类模板 <实际类型名> 对象名 (实参列表);

Compare <int> cmp1;

Compare <int> cmp1(3,7);

(3) 如果在模板外定义成员函数,应该写成类模板形式:

template <class   虚拟特征参数>

函数类型 类模板名 <虚拟类型参数》::成员函数名(函数形参列表) {...}

(4)类模板的类型参数可以是一个或多个,每个类型前面必须加class,如:

template <class  T1,class T2>

class someclass

{....};

在定义对象时分别代入实际的类型名,如

someclass<int,double> obj;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值