C++类模板

与函数模板相同,往往有时候对好几个功能相似的类,可以使用类模板。

C++类模板

#include <iostream>
using namespace std;
template<class numtype> //声明一个模板,虚拟类型名为numtype
class compare //类模板名为compare
{
public:
    compare(numtype x,numtype y)
    {
        this->x=x;
        this->y=y;
    }
 
 
    numtype max()
    {
        return x>y?x:y;
    }
 
 
    numtype min()
    {
        return x<y?x:y;
    }
    numtype mean();
private:
    numtype x,y;
};
template<class numtype>
numtype compare<numtype>::mean()
{
    return (x+y)/2;
}
 
 
int main()
{
    compare<int> comp1(1,2);
    cout << "max is" << comp1.max() << endl;
    cout << "min is" << comp1.min() << endl;
    compare<float> comp2(1.5,2.1);
    cout << "max is" << comp2.max() << endl;
    cout << "min is" << comp2.min() << endl;
    cout << "mean is" << comp2.mean() << endl;
    compare<char> comp3('a','b');
    cout << "max is" << comp3.max() << endl;
    cout << "min is" << comp3.min() << endl;
    return 0;
}
 

1.1在声明类模板前要增加一行 template<class 类型参数名>
1.2 numtype只是一个虚拟类型参数名。
1.3在建立对象时,如果指定为int则为int型,指定为float,则为float型。实现“一类多用”
1.4因为类模板包含参数,所以被称为参数化的类。
1.5如果说类是对象的抽象,那么类模板是类的抽象,类是类模板的实例。
1.6使用类模板:
compare <int> cmp1(1,2);
1.7在类外使用类模板函数
template <class numtype>
numtype compare<numtype>::mean()
{
return (x+y)/2;
}

C++类模板的使用步骤

1.1先写出一个实际的类,而不是类模板。
1.2将此类中的int等改成一个指定的虚拟类型名。
1.3在类的声明前加一行:
template <class 虚拟化参数(如:numtype)>
1.4用类模板定义对象时用以下形式:
compare <int> comp1(1,2);
1.5在模板外定义成员函数,应写成类模板的形式。
template<class numtype>
numtype compare<numtype>::mean(){}

C++类模板其他

1.1类模板的类型参数可以有一个或者多个,每个类型前面都必须加class,如:
template<class T1,class T2>
class someclass
{...};
在定义对象的时候分别带入实际的类型名,如:
someclass <int,double> obj;
1.2和使用类一样,在使用类模板的时候要注意其作用域,只能在其有效作用域内用它定义对象。
1.3模板可以有层次,一个类模板可以作为基类,派生出派生类的模板类。




 
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值