注意:本文中代碼均使用 Qt 開發(fā)編譯環(huán)境
#include <QCoreApplication>
#include <QDebug>
class Student
{
public:
int id;
double gpa; //平均分
};
template<class T>
class Store
{
public:
Store()
: haveValue(false)
{}
T getItem();
void addItem(T x);
private:
T item; //用于存放任意類型的數(shù)據(jù)
volatile bool haveValue;
};
template<class T>
T Store<T>::getItem()
{
if(haveValue){
return item;
}else {
exit(1);
}
}
template<class T>
void Store<T>::addItem(T x)
{
haveValue = true;
item = x;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Store<int> s1,s2;
s1.addItem(3);
s2.addItem(-7);
qDebug() << s1.getItem() << " " << s2.getItem();
Student g = {1000,23};
Store<Student> s3;
s3.addItem(g);
qDebug() <<"The student id is: " << s3.getItem().id;
Store<double> d;
d.addItem(0.5);
qDebug() << d.getItem();
return a.exec();
}