C++中類模板的使用

來源:互聯網
上載者:User

標籤:c++   類模板   編程   

類模板是類的抽象,類是類模板的執行個體。

聲明類模板:template<class T1,class T2...>//可聲明多個型別參數

關於類模板的使用謹記一點。用類模板執行個體化的類中實參數類型去代替聲明時的型別參數名。

如聲明:template <class T1,class T2>

class Compare
{
public:
    Compare(T1 a,T2 b):x(a),y(b){};
    void display();
private:
    T1 x;
    T2 y;
};

執行個體化:Compare<int,float> cmp(2,3.14);

此處即用int代替模板中的T1,float代替模板中的T2;

下面以兩段程式說明類模板的使用:

1、在類模板內定義成員函數,含兩個類型名:

#include<iostream>using namespace std;template <class T1,class T2>class Compare{public:    Compare(T1 a,T2 b):x(a),y(b){};    void display()    {    cout<<x<<endl;    cout<<y<<endl;    }private:    T1 x;    T2 y;};int main(){    Compare<int,float> cmp(2,3.14);    cmp.display();    return 0;}

2、在類模板外定義成員函數,含兩個類型名:

#include<iostream>using namespace std;template <class T1,class T2>class Compare{public:    Compare(T1 a,T2 b):x(a),y(b){};    void display();private:    T1 x;    T2 y;};template <class T1,class T2>//此處還需在聲明一次  不然會報錯void Compare<T1,T2>::display(){    cout<<x<<endl;    cout<<y<<endl;}int main(){    Compare<int,float> cmp(2,3.14);    cmp.display();    return 0;}



C++中類模板的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.