程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++ 模板類解析

C++ 模板類解析

編輯:C++入門知識

具體模板類作用這邊就不細說了,下面主要是描述下模板類的使用方法以及注意的一些東西。

#include <iostream>
using namespace std;
template <typename 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)將此類中准備改變的類型名(如int要改變為float或char)改用一個自己指定的虛擬類型名(如上例中的numtype)。

3)在類聲明前面加入一行,格式為
          template <typename 虛擬類型參數>,如
          template <typename numtype> //注意本行末尾無分號
          class Compare
          {…}; //類體

4)用類模板定義對象時用以下形式:
          類模板名<實際類型名> 對象名;
          類模板名<實際類型名> 對象名(實參表列);
          如
          Compare<int> cmp;
          Compare<int> cmp(3,7);

    說明:Compare是類模板名,而不是一個具體的類,類模板體中的類型numtype並不是一個實際的類型,只是一個虛擬的類型,無法用它去定義對象。
必須用實際類型名去取代虛擬的類型,具體的做法是:
       Compare <int> cmp(4,7);
      即在類模板名之後在尖括號內指定實際的類型名,在進行編譯時,編譯系統就用int取代類模板中的類型參數numtype,這樣就把類模板具體化了,或者說實例化了。

5) 如果在類模板外定義成員函數,應寫成類模板形式:
         template <class 虛擬類型參數>
         函數類型 類模板名<虛擬類型參數>::成員函數名(函數形參表列) {…}

    eg:

      template <nametype numtype>
           numtype Compare<numtype>::max( )
           {{return (x>y)?x:y;}

補充說明

1)類模板的類型參數可以有一個或多個,每個類型前面都必須加class,如
          template <class T1,class T2>
          class someclass
          {…};
          在定義對象時分別代入實際的類型名,如
          someclass<int,double> obj;

2)和使用類一樣,使用類模板時要注意其作用域,只能在其有效作用域內用它定義對象。

 

參考:http://see.xidian.edu.cn/cpp/biancheng/view/213.html

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved