OJ-类模版

来源:互联网 发布:长相忆五色石南叶 知乎 编辑:程序博客网 时间:2024/06/14 16:07
有一种类,海纳百川,可以对任意类型的数据进行存取,造就这个传奇的,就是模板。

下面的程序中,定义一个类模板,但其中有些成份漏掉了,请你将他们补足,使程序能正确运行,得到要求的输出结果。

Input
一个整数和一个小数,将通过putElem函数存于相应的对象实例中


Output
通过getElem()取出相应对象中存入的数据,并且输出,浮点型保留两位小数


Sample Input
240 56.7183
Sample Output
240
56.72

//************* begin *****************#include <iostream>#include <cstdlib>#include <iomanip>using namespace std;template <class T >//类模板,实现对任意类型数据进行存取class Store{private:    T item;        //用于存放任意类型的数据    int haveValue;  //用于标记item是否为空,0表示为空,1表示有数据public:    Store();          //默认构造构造函数    T getElem();      //提取数据,返回item的值    void putElem(T x);//存入数据};template<class T>//默认构造构造函数的实现Store<T>::Store(void):haveValue(0){};template<class T>   //提取数据函数的实现,返回item中的数据T Store<T>::getElem(void){    if (haveValue==0) //如果试图提取未初始化的数据,则终止程序    {        cout<<"NO item present!\n";        exit(1);    }    return item;}template<class T>//存入数据的实现void Store<T>::putElem(T x){    haveValue=1;    item = x;}//************* end *****************int main(){    Store<int> si;    Store<double> sd;    int i;    double d;    cin>>i>>d;    si.putElem(i);    sd.putElem(d);    cout <<setiosflags(ios::fixed)<<setprecision(2);    cout<<si.getElem()<<endl;    cout<<sd.getElem()<<endl;    return 0;}

!!每一个函数前面要加上

template <class T >
切记切记。


@ Mayuko


0 0