wine.h
#ifndef WINE_H_
#define WINE_H_
#include<string>
#include<valarray>
// delclarations and implementaions of Pair
template <class T1, class T2>
class Pair
{
private:
T1 a;
T2 b;
public:
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;
}
// delclarations of Wine
typedef std::valarray<int> ArrayInt;
typedef Pair<ArrayInt, ArrayInt> PairArray;
class Wine:private std::string,private PairArray
{
private:
int yrs;
public:
Wine();
Wine(const char* l, int y, const int yr[], const int bot[]);
Wine(const char* l, int y);
void GetBottles();
const std::string& Label() const
{
return (std::string&) *this;// don't forget &
};
int sum();
void Show();
};
#endif
wine.cpp
// implementations of Wine
// as did not use template for class Wine,so place implementations
// in seperate file
// attention, the use of valarray(array,elements_num)
#include<iostream>
#include"wine.h"
using std::cin;
using std::cout;
using std::endl;
// part from base-class must be created in member initializer
// using their own constructors
Wine::Wine() :std::string(""), PairArray(ArrayInt(0), ArrayInt(0)), yrs(0) {};
Wine::Wine(const char* l, int y, const int yr[], const int bot[]) : std::string(l),
PairArray(ArrayInt(yr, y), ArrayInt(bot, y)), yrs(y) {};
Wine::Wine(const char* l, int y) :std::string(l), PairArray(ArrayInt(y), ArrayInt(y)),
yrs(y) {};
void Wine::GetBottles()
{
cout << "Enter pair of year and number of bottles.\n";
for (int i = 0; i < yrs; i++)
{
cout << "Year: ";
cin >> PairArray::first()[i];
cout << "bottles: ";
cin >> PairArray::second()[i];
}
}
int Wine::sum()
{
return PairArray::second().sum();
}
void Wine::Show()
{
cout << "Wine: " << Label() << endl;
cout << "\t" << "year" << "\t" << "Bottles" << endl;
for (int i = 0; i < yrs; i++)
cout << "\t" << PairArray::first()[i] << "\t" << PairArray::second()[i] << endl;
}
main.cpp
// pe14-1.cpp -- using Wine class with containment
#include <iostream>
#include "wine.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; // use sum() method
cout << "Bye\n";
cin.get();
cin.get();
return 0;
}