Template模版实例(C++)


2011,3,29
编程环境VC++6.0

1.函数模版

template<class/typename T>
类型名 函数名(参数表)
{函数体的定义}

2.类模版声明语法格式
template<模版参数表>
class 类名
{类成员声明}

3.类成员函数定义
template <模版参数表>
类型名 类名<T>::函数名(参数表)

4.对象建立
模版<模版参数表>   对象名1,...,对象名n;


5.实例

#include<iostream>
#include<cstdlib>
using namespace std;

struct student//结构体student

{
    int id;
    int gpa;
};

template<class T>
class Store
{
private:
    T item;
    int haveValue;

public:
    Store(void);//默认构造函数

    T GetElem(void);
    void PutElem(T x);
};


//成员函数实现
template <class T>
Store<T>::Store(void):haveValue(0)
{}

template <class T>
T Store<T>::GetElem(void)
{
    if(haveValue==0)
    {
        cout<<"ERROR!"<<endl;
        exit(1);
    }
    return item;
}

template<class T>
void Store <T>::PutElem(T x)
{
    haveValue++;
    item=x;
}

//主函数
int main()
{
    student g={1000,23};
    Store <int> S1,S2;
    Store <student> S3;

    Store<double> D;
    S1.PutElem(3);
    S2.PutElem(-7);
    cout<<S1.GetElem()<<" "<<S2.GetElem()<<endl;
    S3.PutElem(g);
    cout<<"ID="<<S3.GetElem().id<<endl;
    cout<<"GPA="<<S3.GetElem().gpa<<endl;
    cout<<"D"<<endl;
    cout<<D.GetElem()<<endl;
}

运行结果:

你可能感兴趣的:(Template模版实例(C++))