#include<iostream>#include<string>#include<valarray>#include"pair.h"typedef std::valarray<int> ArrayInt;typedef pair<ArrayInt, ArrayInt> pairArray;using std::string;using std::cout;using std::cin;using std::endl;classwine{private:
string label;//wine labelint year;//number of year
pairArray data;//vintage year and botnumpublic:wine():label("none"),year(0),data(ArrayInt(),ArrayInt()){}wine(constchar* l,int y,constint yr[],constint bot[]);wine(constchar*l,int y);voidgetBottles();voidshow()const;intsum()const{return data.second().sum();}const string&Label(){return label;}};
wine::wine(constchar* l,int y,constint yr[],constint bot[]):label(l),year(y),data(ArrayInt(yr,y),ArrayInt(bot,y)){}
wine::wine(constchar*l,int y):label(l),year(y),data(ArrayInt(0, y),ArrayInt(0, y)){}void wine::getBottles(){
cout <<"enter "<<Label()<<" data for "<< year <<"year(s)."<< endl;for(int i =0; i < year;++i){
cout <<"Enter year: ";
cin >> data.first()[i];
cout <<"Enter bottles for that year: ";
cin >> data.second()[i];}}void wine::show()const{
cout <<"Wine: "<< label << endl;
cout <<"\tYear\tBottles\n";for(int i =0; i < year; i++)
cout <<'\t'<< data.first()[i]<<'\t'<< data.second()[i]<< endl;}
测试程序
#include<iostream>#include"wine.h"intmain(void){using std::cin;using std::cout;using std::endl;
cout <<"Enter name of wine: ";char lab[50];
cin.getline(lab,50);
cout <<"Enter number of years: ";int yrs;
cin >> yrs;
wine holding(lab, yrs);// store label, years, give arrays yrs elements
holding.getBottles();// solicit input for year, bottle count
holding.show();// display object contentsconstint YRS =3;int y[YRS]={1993,1995,1998};int b[YRS]={48,60,72};// create new object, initialize using data in arrays y and b
wine more("Gushing Grape Red", YRS, y, b);
more.show();
cout <<"Total bottles for "<< more.Label()// use Label() method<<": "<< more.sum()<< endl;// use sum() method
cout <<"Bye\n";system("pause");return0;}