2015-06-28 14:53:53 OJ期末模考E

博客围绕能对任意类型数据进行存取的类模板展开,给出了一个类模板代码框架,其中部分成份缺失,需补足代码使程序正确运行。程序通过putElem函数存入数据,getElem函数取出数据,还给出了输入输出示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem E: B1 能存各种类型数据的Store

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 221  Solved: 160
[Submit][Status][Web Board]

Description

有一种类,海纳百川,可以对任意类型的数据进行存取,造就这个传奇的,就是模板。

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

请提交beginend部分的代码。

//************* 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!\n";

        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;

}

Input

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

Output

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

Sample Input

240 56.7183

Sample Output

240

56.72

 

 

 

Submit:

#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
template<class T>//(1)类模板,实现对任意类型数据进行存取
class Store
{
private:
    T item;        //用于存放任意类型的数据
    int haveValue;  //用于标记item是否为空,0表示为空,1表示有数据
public:
    Store();          //默认构造构造函数
    T getElem();      //(2)提取数据,返回item的值
    void putElem(T x);//存入数据
};
template<class T>//(3)默认构造构造函数的实现
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)//(4)存入数据的实现
{
    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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值