c++:类模板

#include<iostream>
#include<cstdlib>
using namespace std;
struct Student{
	int id;
	float 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 << "no item present!" << endl;
		exit(1);
	}
	return item;
}
template<class T>
void Store<T>::putElem(T x)
{
	haveValue++;
	item = x;
}
void main()
{
	Student g = { 1000, 23.0};
	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 << "the student id is:" << S3.getElem().id << endl;
	cout << "object D:";
	cout << D.getElem() << endl;
}

posted on 2014-08-18 20:52  _noname  阅读(96)  评论(0编辑  收藏  举报