当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C++类模板实例说明

C++类模板实例说明

2018年09月12日  | 移动技术网IT编程  | 我要评论

一、类模板(template)

类模板是后期c++加入的一种可以大大提高效率的方法

关键字template

用法:

template <模板参数表>   ----->模板参数表一般格式为class (标识符)

class (类名)

{

     //....

}

二、举个栗子

我们要写一个比较类,类里面有两个私有成员

在类里有求私有成员中的最大值和最小值的两个公有成员

用来判断两个数的大小

下面我们来进行有无类模板的比较

(1)不用类模板

代码块:

[cpp] view plain copy

class compare  

{  

    public:  

        compare(int a,int b)//构造函数,用于初始化  

        {  

            x = a;  

            y = b;  

        }  

        int max()//求较大值  

        {  

            return (x>y)?x:y;  

        }  

        int min()//求较小值  

        {  

            return (x<y)?x:y;  

        }  

    private:  

        int x;  

        int y;    

};  

分析:

我们会发现,这个类只能用于比较整形的大小

比如3,5;调用max返回5,调用min返回3

但是如果比较的是浮点数,那就不可以了

(2)用类模板

代码块:

[cpp] view plain copy

template <class type>  

class compare  

{  

    public:  

        compare(type a,type b)  

        {  

            x = a;  

            y = b;  

        }  

        type max()  

        {  

            return (x>y)?x:y;  

        }  

        type min()  

        {  

            return (x<y)?x:y;  

        }  

    private:  

        type x;  

        type y;  

};  

分析:

通过对比发现,这两块代码差别并不是很大,仅仅是增加了关键字

还有类型type替换之前的整型int

在main函数定义时,就可以定义不同类型的对象了

main函数代码:

[cpp] view plain copy

int main(void)  

{     

    compare<int> c1(3,5);  

    cout<<"最大值:"<<c1.max()<<endl;  

    cout<<"最小值:"<<c1.min()<<endl;  

      

    compare<float> c2(3.5,3.6);  

    cout<<"最大值:"<<c2.max()<<endl;  

    cout<<"最小值:"<<c2.min()<<endl;  

      

    compare<char> c3('a','d');  

    cout<<"最大值:"<<c3.max()<<endl;  

    cout<<"最小值:"<<c3.min()<<endl;  

    return 0;  

}  

三、如何写一个将一个类转化为类模板

(1)写出一个类

(2)将类型需要改变的地方进行替换(如上面的type)

(3)在类的前面加入关键字template以及函数参数表

(4)定义对象的格式     类名+<type>+ xx(参数)

比如上面的compare<int> c1(3,5);

(5)切记,模板函数如果定义在类体外,需要在前面加上一行template <函数参数表>。并在类模板名后面用尖括号加上<虚拟函数参数>

比如

template<class type>

type compare <type>::max()

{

       //.....

 一个模板中可以具有多个参数,即可以在一个模板中声明多个自定义的类型,如下面这句话:

template<class t1,class t2>

  而我们就可以利用这两个参数声明一个具有2种类型的成员。下面我用一个程序说下演示一下这个问题:

[cpp] view plain copy

#include <iostream>  

#include <string>  

using namespace std;  

template<class t1,class t2=string>  

class show  

{  

public:  

    void show1(t1 &a){cout<<"show1:"<<a<<endl;}  

    void show2(t2 &a){cout<<"show2:"<<a<<endl;}  

};  

   

int main()  

{  

    show<int> a;  

    int temp1=5;  

    string temp2="hello,c++!";  

    a.show1(temp1);  

    a.show2(temp2);  

    return 0;  

}  

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网