Pair.cpp
#include
using namespace std;
//p580
template <class T1,class T2>
class Pair{
private:
T1 a;
T2 b;
public:
void setFirst(const T1 &t1)
{
a=t1;
}
void setSecond(const T2 &t2)
{
b=t2;
}
T1 &first();
T2 &second();
T1 first()const {return a;};
T2 second()const {return b;};
Pair(const T1 &aval,const T2 &bval):a(aval),b(bval){};
Pair(){};
};
template <class T1,class T2>
T1 &Pair<T1,T2>::first()
{
return a;
}
template <class T1,class T2>
T2 &Pair<T1,T2>::second()
{
return b;
}
Wine.cpp
#include
//#include
#include
#include
#include “Pair.cpp”
using namespace std;
typedef valarray
typedef Pair<ArrayInt,ArrayInt> PairArray;
class Wine{
private:
string label;
PairArray pa;
int yearNum;//永远存储年数,即一共有几种年份的
public:
Wine(const string l,int y,const int yr[],int bot[])
{
label=l;
//int leny=sizeof(yr);//先获取长度
//int lenb=sizeof(bot);
//yearNum=leny;//yr[]数组中存放的是年份
yearNum=y;//已经指明了长度
ArrayInt f(yr,y);//构造valarray
ArrayInt b(bot,y);
pa.setFirst(f);
pa.setSecond(b);
}
Wine(const string l,int y)
{
label=l;
pa.setFirst(ArrayInt(y));
pa.setSecond(ArrayInt(y));
yearNum=y;
}
void GetBottles()
{
int len=yearNum;
int i=0;
while(i<len)
{
cout<<”Enter year:”;
cin>>pa.first()[i];//这个表达式是不是很奇怪?
//pa.first()返回的是a,而a的类型是valarry,这个就不奇怪了吧,哈哈
cin.get();//记得吃掉这个回车;
cout<<”Enter bottles for that year:”;
cin>>pa.second()[i];
cin.get();
i++;
}
}
string &Label()
{
return label;
}
int sum()
{
return pa.second().sum();
}
void show()
{
int len=yearNum;
int i=0;
cout<<”Wine:”<<label<<endl;
cout<<” year bottols”<<endl;
for(;i<len;i++)
{
cout<<” “<<pa.first()[i]<<” “<<pa.second()[i]<<endl;
}
}
};
main141.cpp
#include
#include “Wine.cpp”
using namespace std;
void main141()
{
cout<<”Enter name of wine:”;
string lab;
cin>>lab;
//getline(cin,lab);//用getline,因为可能会有空格
//cin.get();
cout<<”Enter the number of years:”;
int yrs;
cin>>yrs;
Wine holding(lab,yrs);
holding.GetBottles();
holding.show();
const int YRS=3;
int y[YRS]={1993,1995,1998};
int b[YRS]={48,60,72};
Wine more(“Gushagning Grap Red”,YRS,y,b);
more.show();
cout<<”Total bottles for “<<more.Label()<<”:”<<more.sum()<<endl;
cout<<”Byes”<<endl;
cin.get();
};
—————————————————————————————————————————————————— //写的错误或者不好的地方请多多指导,可以在下面留言或者给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。 转载请注明出处:https://www.royalchen.com/ author:royalchen Email:royalchen@royalchen.com ———————————————————————————————————————————————————
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/cprimerplus第六版课后编程题答案141/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!