用template<class 标识符>声明。
#include<iostream.h>
#include<stdlib.h>
struct Student //结构体
{
int id; //学号
float gpa; //平均分
};
template<class T> //类模版
class Store
{
T item; //类模版:实现对任意类型数据存取
int haveValue; //用于标记item是否被存入内容
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<<"No item present!"<<endl;
exit(1);}
return item; //返回item中存放的数据
}
template<class T>
void Store<T>::PutElem(T x)
{
haveValue++; //将haveValue置为True,表示item中存入数值
item=x;
}
void main(void)
{
Student g={1000,23};
Store<int>S1,S2; //S1,S2为整形Store对象
Store<Student>S3; //S3为student型Store对象
Store<double>D;
S1.PutElem(3);
S2.PutElem(-7);
cout<<S1.GetElem()<<" "<<S2.GetElem()<<endl;
S3.PutElem(g);
cout<<"The student id is "<<S3.GetElem().id<<endl;
cout<<"Retrieving object D"<<endl;
cout<<D.GetElem()<<endl; //输出对象D的数据成员
//由于D未经初始化,在执行函数D.GetElem()时出错
}