您的位置:首页 > 编程语言 > C语言/C++

c++不常用功能之——类模板

2016-05-03 20:30 501 查看
类模板是对类的抽象,即对类中的函数和数据进行参数化。类模板中的成员函数为函数模板。
#include<iostream>
usingnamespacestd;
//定义结构体
structStudent{
intid;
floataverage;
};
//类模板
template<classT>
classStore{
public:
Store(void);
TGetElem(void);
voidPutElem(Tx);
private:
Titem;
inthaveValue;
};
//以下是成员函数的实现,主要,类模板的成员函数都是函数模板
template<classT>
Store<T>::Store(void):haveValue(0){
}
template<classT>
TStore<T>::GetElem(void){
	if(haveValue==0){
		cout<<"item没有存入数据!"<<endl;
exit(1);
}
	returnitem;
}
//存入数据的函数实现
template<classT>
voidStore<T>::PutElem(Tx){
	haveValue=1;
	item=x;
}
intmain(){
//声明Student结构体类型变量,并赋值
	Studentg={103,93};
	Store<int>S1,S2;
	Store<Student>S3;
S1.PutElem(7);
S2.PutElem(-1);
	cout<<S1.GetElem()<<""<<S2.GetElem()<<endl;
S3.PutElem(g);
	cout<<"Thestudentidis"<<S3.GetElem().id<<endl;
	return0;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: