WINE.h
#pragma once
#ifndef WINE_H_
#define WINE_H_
#include<valarray>
#include<string>
template <class T1,class T2>
class Pair {
private:
T1 a;
T2 b;
public:
Pair();
void setfist(const T1 & y) { a = y; };
void setscond(const T2 & bo) { b = bo; };
T1 & first();
T2 & second();
T1 fist()const{return a; };
T2 second()const{return b; };
Pair(const T1 & y, const T2 & b) :year(y), bottle(b) {};
};
typedef std::valarray<int> ArrayInt;
typedef Pair<ArrayInt, ArrayInt>PairArray;
class Wine {
private:
std::string str;
PairArray pa;
int years;
public:
Wine(const std::string & l, int y, const int yr[], const int bot[]);
Wine(const std::string & l, int y);
void GetBottles();//提示用户输入年份
std::string & Label(){return str;};//返回葡萄酒的名称
int sum() {return pa.second().sum();};//返回瓶数的总和
void Show()const;
};
template<class T1, class T2>
inline Pair<T1, T2>::Pair()
{
a = 0;
b = 0;
}
template<class T1,class T2>
T1 & Pair<T1,T2>::first()
{
return a;
}
template<class T1,class T2>
T2 & Pair<T1, T2>::second()
{
return b;
}
#endif
WINE.cpp
#include "WINE.h"
#include <iostream>
Wine::Wine(const std::string & l, int y, const int yr[], const int bot[])
{
str = l;
years = y;
ArrayInt f(yr, y);//创建valarray数组
ArrayInt b(bot, y);
pa.setfist(f);
pa.setscond(b);
}
Wine::Wine(const std::string & l, int y)
{
str = l;
pa.setfist(ArrayInt(y));
pa.setscond(ArrayInt(y));
years = y;
}
void Wine::GetBottles()
{
using std::cin;
using std::cout;
for (int i = 0; i < years; i++)
{
cout << "Enter years: ";
cin >> pa.first()[i];//pa.first()返回一个valarray<int> a,所以这里等价于valarray<int>a[i]
cout << "Enter bottle for the year: ";
cin >> pa.second()[i];
}
}
void Wine::Show() const
{
using std::cout;
using std::endl;
cout << "Wine:" << str << endl;
cout << "\tYear\tBottle" << endl;
for (int i = 0; i < years; i++)
{
cout<<"\t"<< pa.fist()[i] << "\t" << pa.second()[i] << endl;
}
}
main.cpp
#include <iostream>
#include "WINE.h"
int main()
{
using std::cout;
using std::endl;
using std::cin;
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);
holding.GetBottles();
holding.Show();
const int YRS = 3;
int y[YRS] = { 1993,1995,1998 };
int b[YRS] = { 48,60,72 };
Wine more("Gushing Grape Red", YRS, y, b);
more.Show();
cout << "Total bottles for " << more.Label()
<< ": " << more.sum() << endl;
cout << "Bye\n";
cin.get();
cin.get();
return 0;
}