C++类模版

用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()时出错
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值