2015-06-28 14:53:53 OJ期末模考E
作者:互联网
Problem E: B1 能存各种类型数据的Store类
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 221 Solved: 160
[Submit][Status][Web Board]
Description
有一种类,海纳百川,可以对任意类型的数据进行存取,造就这个传奇的,就是模板。
下面的程序中,定义一个类模板,但其中有些成份漏掉了,请你将他们补足,使程序能正确运行,得到要求的输出结果。
请提交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!\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;
}
标签:模考,06,void,53,item,putElem,haveValue,数据,Store 来源: https://blog.csdn.net/cddlsz/article/details/46671481