template《class T》到底怎么用呢!
今年刚学的数据结构,可是实验书上的template<class T>就有点看不懂了。不知道到底怎么用,希望高手指点一下,最好有c++的源代码编写的例题举例说明下,在这里多谢了!,同时我也是刚加入《编程中国》,希望结交更多的编程爱好者!
对内置的 和 typedef 的感觉差不多
照着抄的:
#include <iostream>
#include <cstdlib>
using namespace std;
class student
{
private:
int id;
float gpa;
public:
student(int a = 4, float b = 5 ):id(a),gpa(b){}
/* student(const student &s)
{
id = s.id;
gpa = s.gpa;
}
*/
int Get(){ return id;}
};
template<class T>
class Store
{
private:
T item;
int haveValue;
public:
Store(void);
Store(T x);
T GetElem(void);
//void PutElem(T x);
};
template<class T>
Store<T>::Store(void):haveValue(0)
{}
template<class T>
Store<T>::Store( T x):haveValue(1), item(x)
{}
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;
}*/
int main()
{
student g(1000, 23);
Store<int> S1(2), S2(8);
Store<student> S3(g);
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().Get()<<endl;
return 0;
}