转载自:http://www.jizhuomi.com/software/55.html
什么是类模板呢?类模板就是为类声明一种模板,使得类中的某些数据成员,或某些成员函数的参数,又或者是某些成员函数的返回值可以取任意的数据类型,包括基本数据类型和自定义数据类型。
类模板的声明形式如下:
template <模板参数表>
类声明
class 标识符(指明可以接受一个类型参数,就是说这是个不固定的类型,用它生成类时才会产生真正的类型)。
#include "stdafx.h"
#include <iostream>
using namespace std;
template <class T>
class Store
{
public:
Store(void);
void PutElem(T x);
T GetElem(void);
private:
T item;
int haveValue;
};
template <class T>
Store<T>::Store(void):haveValue(0)
{
}
template <class T>
void Store<T>::PutElem(T x)
{
item = x;
}
template <class T>
T Store<T>::GetElem(void)
{
return item;
}
int _tmain(int argc, _TCHAR* argv[])
{
Store< int> S1, S2;//也可定义为int,double等。
S1.PutElem(7.8);
S2.PutElem(-1);
cout <<"S1:"<<S1.GetElem()<<endl;
cout <<"S2:"<<S2.GetElem()<<endl;
//也可使用自定义的结构体变量
struct Student
{
int id;
float score;
};
Store<Student> S3;
Student g = { 103, 93 };
S3.PutElem(g);
cout << "student id is "<<S3.GetElem().id << endl;
cout << "student score is " << S3.GetElem().score<<endl;
cin.ignore();
return 0;
}