zoukankan      html  css  js  c++  java
  • [YTU]_2631( B1 能存各种类型数据的Store类)

    题目描述

    有一种类,海纳百川,可以对任意类型的数据进行存取,造就这个传奇的,就是模板。
    下面的程序中,定义一个类模板,但其中有些成份漏掉了,请你将他们补足,使程序能正确运行,得到要求的输出结果。
    请提交begin到end部分的代码。
    //************* begin *****************
    #include <iostream>
    #include <cstdlib>
    #include <iomanip>
    using namespace std;
    ______(1)_______//类模板,实现对任意类型数据进行存取
    class Store
    {
    private:
        T item;        //用于存放任意类型的数据
        int haveValue;  //用于标记item是否为空,0表示为空,1表示有数据
    public:
        Store();          //默认构造构造函数
        __(2)__ getElem();      //提取数据,返回item的值
        void putElem(T x);//存入数据
    };
    ______(3)_______//默认构造构造函数的实现
    Store<T>::Store(void):haveValue(0){};
    template<class T>   //提取数据函数的实现,返回item中的数据
    T Store<T>::getElem(void)
    {
        if (haveValue==0) //如果试图提取未初始化的数据,则终止程序
        {
            cout<<"NO item present! ";
            exit(1);
        }
        return item; 
    }
    template<class T>//存入数据的实现
    ______(4)_______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;
    }

    输入

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

    输出

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

    样例输入

    240 56.7183

    样例输出

    240
    56.72
    #include <iostream>
    #include <cstdlib>
    #include <iomanip>
    using namespace std;
    template <class T>
    class Store
    {
        private:
            T item;
            int haveValue;
        public:
            Store();
            T getElem();
            void putElem(T x);
    };
    template <class T>
    Store<T>::Store(void):haveValue(0){};
    template<class T>
    T Store<T>::getElem(void)
    {
        if(haveValue==0)
        {
            cout<<"NO item present!
    ";
            exit(1);
        }
        return item;
    }
    template<class T>
    void Store<T>::putElem(T x)
    {
        haveValue=1;
        item=x;
    }
    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;
    }
    

  • 相关阅读:
    CodeForces
    网络流
    poj 2185
    树的分治学习
    数位DP
    URAL 1969. Hong Kong Tram
    hdu 4759 Poker Shuffle
    hdu3712 Detector Placement
    分块思想
    莫比乌斯反演
  • 原文地址:https://www.cnblogs.com/sxy201658506207/p/7586352.html
Copyright © 2011-2022 走看看