//wine.h
#ifndef _PARI_H
#define _PARI_H
#include <valarray>
#include <string>
#include <iostream>
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;
}
typedef valarray<int> ArrayInt;
typedef Pair<ArrayInt,ArrayInt> PairArray;
class Wine: private std::string,private PairArray
{
private:
int yearNum;//永远存储年数,即一共有几种年份的
public:
Wine(const string l,int y,const int yr[],int bot[]) ;
Wine(const string l,int y) ;
void GetBottles() ;
const string &Label() ;
int sum() ;
void show() ;
};
Wine::Wine(const string l,int y,const int yr[],int bot[]) :std::string(l)
{
yearNum=y;//已经指明了长度
ArrayInt f(yr,y);//构造valarray<int>数组
ArrayInt b(bot,y);
PairArray::setFirst(f);
PairArray::setSecond(b);
}
Wine::Wine(const string l,int y):std::string(l)
{
PairArray::setFirst(ArrayInt(y));
PairArray::setSecond(ArrayInt(y));
yearNum=y;
}
void Wine::GetBottles()
{
int len=yearNum;
int i=0;
while(i<len)
{
cout<<"Enter year:";
cin>>PairArray::first()[i];//这个表达式是不是很奇怪?
//pa.first()返回的是a,而a的类型是valarry,这个就不奇怪了吧,哈哈
cin.get();//记得吃掉这个回车;
cout<<"Enter bottles for that year:";
cin>>PairArray::second()[i];
cin.get();
i++;
}
}
const std::string & Wine ::Label()
{
return (const std::string&)*this;
}
int Wine :: sum()
{
return PairArray::second().sum();
}
void Wine::show()
{
int len=yearNum;
int i=0;
cout<<"Wine:"<<std::string(*this)<<endl;
cout<<" year bottols"<<endl;
for(;i<len;i++)
{
cout<<" "<<PairArray::first()[i]<<" "<<PairArray::second()[i]<<endl;
}
}
#endif
//main.cpp
#include<iostream>
#include"wine.h"
//#include"pair.h"
int main()
{
using std ::cin;
using std::cout;
using std::endl;
cout <<"enter name ; ";
char lab[50];
cin.getline(lab,50);
cout<<"enter 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("gushing",YRS,y,b);
more.show();
cout<<"totlal bottles for" <<more.Label();//<<"; "<<more.sum()<<endl;
cout<<"end"<<endl;
system("pause");
return 0;
}
14.2
最新推荐文章于 2024-06-14 16:26:54 发布