c++通用模板类(template class)定义实现详细介绍

     有时,有两个或多个类,其功能是相同的,仅仅是数据类型不同,如下面语句声明了一个类:class Compare_int { public : Compare(int a,int b) { x=a; y=b; } int max( ) { return (x>y)?x:y; } int min( ) { return (x&...


有时,有两个或多个类,其功能是相同的,仅仅是数据类型不同,如下面语句声明了一个类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class  Compare_int
{
    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,y;
};

其作用是对两个整数作比较,可以通过调用成员函数max和min得到两个整数中的大者和小者。如果想对两个浮点数(float型)作比较,需要另外声明一个类:

1
2
3
4
5
6
7
8
9
10
11
12
class  Compare_float
{
    public  :
    Compare( float  a, float  b)
    {x=a;y=b;}
    float  max( )
    { return  (x>y)?x:y;}
    float  min( )
    { return  (x<y)?x:y;}
    private  :
    float  x,y;
}

显然这基本上是重复性的工作,应该有办法减少重复的工作。

   C++在发展的后期增加了模板(template)的功能,提供了解决这类问题的途径。可以声明一个通用的类模板,它可以有一个或多个虚拟的类型参数,如对以上两个类可以综合写出以下的类模板:

1
2
3
4
5
6
7
8
9
10
11
12
13
template  < class  numtype>  //声明一个模板,虚拟类型名为numtype
class  Compare  //类模板名为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;
};

请将此类模板和前面第一个Compare_int类作一比较,可以看到有两处不同:

1)声明类模板时要增加一行  

1
template  < class  类型参数名>

2)原有的类型名int换成虚拟类型参数名numtype。

   在建立类对象时,如果将实际类型指定为int型,编译系统就会用int取代所有的numtype,如果指定为float型,就用float取代所有的numtype。这样就能实现“一类多用”。由于类模板包含类型参数,因此又称为参数化的类。如果说类是对象的抽象,对象是类的实例,则类模板是类的抽象,类是类模板的实例。利用类模板可以建立含各种数据类型的类。在声明了一个类模板后,怎样使用它?怎样使它变成一个实际的类?

先回顾一下用类来定义对象的方法:

  Compare_int cmp1(4,7); // Compare_int是已声明的类

用类模板定义对象的方法与此相似,但是不能直接写成

  Compare cmp(4,7); // Compare是类模板名

  Compare是类模板名,而不是一个具体的类,类模板体中的类型numtype并不是一个实际的类型,只是一个虚拟的类型,无法用它去定义对象。

必须用实际类型名去取代虚拟的类型,具体的做法是:

  Compare <int> cmp(4,7);

即在类模板名之后在尖括号内指定实际的类型名,在进行编译时,编译系统就用int取代类模板中的类型参数numtype,这样就把类模板具体化了,或者说实例化了。这时Compare<int>就相当于前面介绍的Compare_int类。

例子:声明一个类模板,利用它分别实现两个整数、浮点数和字符的比较,求出大数和小数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#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 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;
}

运行结果如下:

1
2
3
4
5
6
7 is the Maximum of two integers.
3 is the Minimum of two integers.
93.6 is the Maximum of two float numbers.
45.78 is the Minimum of two float numbers.
a is the Maximum of two characters.
A is the Minimum of two characters.

还有一个问题要说明: 上面列出的类模板中的成员函数是在类模板内定义的。如果改为在类模板外定义,不能用一般定义类成员函数的形式:

  numtype Compare::max( ) {…} //不能这样定义类模板中的成员函数

而应当写成类模板的形式:

  template <class numtype>

  numtype Compare<numtype>::max( )

  {{return (x>y)?x:y;}

归纳以上的介绍,可以这样声明和使用类模板:

先写出一个实际的类。由于其语义明确,含义清楚,一般不会出错。

将此类中准备改变的类型名(如int要改变为float或char)改用一个自己指定的虚拟类型名(如上例中的numtype)。

在类声明前面加入一行,格式为

template <class 虚拟类型参数>,如

template <class numtype> //注意本行末尾无分号

class Compare

{…}; //类体

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

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

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

  Compare<int> cmp;

  Compare<int> cmp(3,7);

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

  template <class 虚拟类型参数>

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


关于类模板的几点说明:

类模板的类型参数可以有一个或多个,每个类型前面都必须加class,如

template <class T1,class T2>

class someclass

{…};

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

  someclass<int,double> obj;

和使用类一样,使用类模板时要注意其作用域,只能在其有效作用域内用它定义对象。

模板可以有层次,一个类模板可以作为基类,派生出派生模板类。

模板类和重载函数一起使用

    两者一起使用时,先考虑重载函数,后考虑模板类,如过再找不到,就考虑类型转换,可能会带来精度的变化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using  namespace  std ;
  //函数模板
template  < class  T>
const  T MAX(T a , T b)
{
    printf ( "%s\n"  "template" ) ;
    return  (a > b) ? a : b ;   
}
int  MAX( int  x ,  int  y)
{
     printf ( "%s\n"  "int int"  );
     return  (x > y) ? x : y ;   
}
int  MAX( char  x ,  int  y)
{
     printf ( "%s\n"  "char int"  );
     return  (x > y) ? x : y ;   
}
int  MAX( int  x ,  char  y)
{
     printf ( "%s\n"  "int char"  );
     return  (x > y) ? x : y ;  
}
int  main()
{
    int    a = 3 , b = 5 ;
    char  x =  'x'  ;
    double  c = 3.4  ;
    cout<<MAX(a , b)<<endl ;  //调用重载函数
    cout<<MAX(c , d)<<endl ;  //无对应的重载函数,则调用模板
   cout<<MAX(a , x)<<endl ;  //重载函数
   cout<<MAX(x , a)<<endl ;  //重载函数
   cout<<MAX(c , a)<<endl ;
    cout<<MAX(a) ;
    system ( "pause" ) ;
    return  0 ; 
}

类定义体外定义的成员函数,应该使用函数模板.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
   using  namespace  std ;
   template  < class  T>
   class  Base
   {
     public  :  
      T a ;
      Base(T b)
      {
        a = b ;  
     
      T getA(){ return  a ;}  //类内定义
      void  setA(T c);  
   } ;
   template  < class  T>    //模板在类外的定义
   void   Base<T>::setA(T c)
    {
      a = c ;          
    }
   int  main()
   {
        Base < int >b(4) ;
        cout<<b.getA() ;
        Base < double > bc(4) ;
        bc.setA(4.3) ;
        cout<<bc.getA() ;
        system ( "pause" ) ;
    return  0 ;  
   }
  • 14
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当我们需要将模板类定义实现分离到不同的文件中时,可以将模板类的声明放在一个头文件中,将模板类实现放在一个cpp文件中。 假设我们有一个模板类`MyClass`的声明: ```c++ // MyClass.h #pragma once template<typename T> class MyClass { public: MyClass(T value); void printValue(); private: T m_value; }; ``` 在模板类定义中,我们只需要声明构造函数和`printValue`函数的方法,而不需要提供函数的具体实现,因为这些实现将在另一个文件中提供。 现在我们需要在一个cpp文件中提供模板类实现: ```c++ // MyClass.cpp #include "MyClass.h" #include <iostream> template<typename T> MyClass<T>::MyClass(T value) : m_value(value) {} template<typename T> void MyClass<T>::printValue() { std::cout << "Value: " << m_value << std::endl; } // 显式实例化模板类 template class MyClass<int>; template class MyClass<float>; ``` 在这个文件中,我们提供了模板类实现,包括构造函数和`printValue`函数的具体代码。此外,我们还需要显式实例化模板类,这将在编译时生成模板类的实例化代码。在这个例子中,我们实例化了`MyClass<int>`和`MyClass<float>`两个型的模板类。 最后,在需要使用模板类的文件中,只需要包含头文件即可: ```c++ // main.cpp #include "MyClass.h" int main() { MyClass<int> obj(42); obj.printValue(); return 0; } ``` 在这个例子中,我们实例化了一个`MyClass<int>`型的对象,并调用了它的`printValue`函数。编译器将在编译时生成实例化的代码,并将其链接到最终的可执行文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值