C++类模板

代码如下:

#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;



}

结果:

C++类模板

CFree5值分析:

C++类模板

附注:代码段中exit(1);可用来表示程序终止的原因,可以被操作系统接收

分析结论:使用类模板用户可以为类定义一种模式,使类中的某些数据,函数成员的参数,返回值或局部变量能取任意类型。

你可能感兴趣的:(C++)