PS:之前文章标题只知道复制之前文章,忘记改名字了,不好意思
这题比较简单,Pair类是个模板类,也需要实例化
winec.h
// winec.h
#ifndef WINEC_H_
#define WINEC_H_
#include <iostream>
#include <string>
#include <valarray>
template<typename T1, typename T2>
class Pair
{
private:
T1 year;
T2 bottles;
public:
Pair(const T1 & yr, const T2 & bt) :year(yr), bottles(bt) {}
Pair() {}
void Set(const T1 & yr, const T2 & bt);
int Sum() const;
void Show(int y) const;
};
template<typename T1, typename T2>
void Pair<T1, T2>::Set(const T1 & yr, const T2 & bt)
{
year = yr;
bottles = bt;
}
template<typename T1, typename T2>
inline int Pair<T1, T2>::Sum() const
{
return bottles.sum();
}
template<typename T1, typename T2>
inline void Pair<T1, T2>::Show(int y) const
{
for (int i = 0; i < y; i++)
std::cout << "\t" << year[i] << "\t" << bottles[i] << std::endl;
}
class Wine
{
private:
typedef std::valarray<int> ArrayInt;
typedef Pair<ArrayInt, ArrayInt> PairArray;
std::string label;
PairArray yb;
int yrs;
public:
// initialize label to l, number of years to y,
// vintage years to yr[], bottles to bot[]
Wine(const char * l, int y, const int yr[], const int bot[]);
// initialize label to l, number of years to y,
// create array objects of length y
Wine(const char * l, int y);
void GetBottles();
std::string & Label();
void Show() const;
int Sum() const;
};
#endif // !WINEC_H_
winec.cpp
#include "winec.h"
#include <iostream>
// winec.cpp
Wine::Wine(const char * l, int y, const int yr[], const int bot[])
{
label = l;
yrs = y;
yb.Set(ArrayInt(yr, yrs), ArrayInt(bot, yrs));
}
Wine::Wine(const char * l, int y)
{
label = l;
yrs = y;
}
void Wine::GetBottles()
{
ArrayInt yr(yrs), bt(yrs);
std::cout << "Enter " << label << " data for " << yrs << " year(s):\n";
for (int i = 0; i < yrs; i++)
{
std::cout << "Enter year: ";
std::cin >> yr[i];
std::cout << "Enter bottles for that year: ";
std::cin >> bt[i];
}
while (std::cin.get() != '\n')
continue;
yb.Set(yr, bt);
}
std::string & Wine::Label()
{
return label;
}
void Wine::Show() const
{
std::cout << "Wine: " << label << std::endl;
std::cout << "\tYear\tBottles\n";
yb.Show(yrs);
}
int Wine::Sum() const
{
return yb.Sum();
}
main.cpp
// pe14-1.cpp -- using Wine class with cintainment
#include <iostream>
#include "winec.h"
int main(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 contents
const int 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;
cout << "Bye\n";
cin.get();
return 0;
}