C++類模板

來源:互聯網
上載者:User

標籤:

代碼如下:

#include <iostream>#include <cstdlib>using namespace std;typedef struct Tstudent      //結構體完整定義{    int nId;    float fGpa;}Tstudent;template <class T>           //模版類class CStroe{public:    CStroe();            //建構函式    T &getElem();        // 返回引用    void putElem(const T &x);       //傳遞類型引用private:    T item;                          //資料    bool haveValue;                 //控制};template<class T> CStroe<T>::CStroe():haveValue(false){}//建構函式初始化template<class T> T& CStroe<T>::getElem()  // 返回引用{    ////控制開關狀態    if(!haveValue)                 {        cout<<"No item present!"<<endl;        //exit(1);    }    return item;}template<class T> void CStroe<T>::putElem(const T &TRec)            //引用(別名)傳遞{    haveValue=true;                      //設定開關狀態    item =TRec;                             //}int main(){    //整形例    CStroe<int> nStu1,nStu2;        //模版類    nStu1.putElem(3);    nStu2.putElem(-7);    cout<<nStu1.getElem()<<""<<nStu2.getElem()<<endl;    //結構類型例    Tstudent tG={1000,23};         //結構體    CStroe<Tstudent> tS3;          //模版類    tS3.putElem(tG);    cout<<"The student ID is "<<tS3.getElem().nId<<"\t"<<"Gpa is"<<tS3.getElem().fGpa<< endl;    //Double類型    CStroe<double> dStu;    cout<<"Retrieving object d...";    cout<<dStu.getElem()<<endl;    getchar();    return 0;}

結果:

CFree5值分析:

附註:程式碼片段中exit(1);可用來表示程式終止的原因,可以被作業系統接收

分析結論:使用類模板使用者可以為類定義一種模式,使類中的某些資料,函數成員的參數,傳回值或局部變數能取任意類型。

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.