typedef Pair<ArrayInt, ArrayInt> PairArray的PairArray data初始化
//Wine包含Pair模板和sting成员#include<iostream>
#include <valarray>
#include<string>
using namespace std;
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;
}
class Wine
{
private:
typedef valarray<int> ArrayInt;//valarray<int> 的用法到底是怎么样的?
typedef Pair<ArrayInt, ArrayInt> PairArray;
string label;
int years;
PairArray data;
public:
Wine() : label("none"), years(0), data(ArrayInt(),ArrayInt()) {}//这里的date为什么要 data(ArrayInt(),ArrayInt()这样初始化,实在不懂?
Wine(const char * l, int y, const int yr[], const int bot[]);
Wine(const char * l, const ArrayInt & yr, const ArrayInt & bot);
Wine(const char * l, const PairArray & yr_bot);
Wine(const char * l, int y);
void GetBottles();
void Show() const;
const string & Label() { return label; }
int sum() const { return data.second().sum(); }
};
Wine::Wine(const char * l, int y, const int yr[], const int bot[])
: label(l), years(y), data(ArrayInt(yr,y),ArrayInt(bot,y) )//data(ArrayInt(yr,y),ArrayInt(bot,y) 这代表什么?
{
}
Wine::Wine(const char * l, const ArrayInt & yr, const ArrayInt & bot)
: label(l), years(yr.size()), data(ArrayInt(yr), ArrayInt(yr))//data(ArrayInt(yr), ArrayInt(yr)) 这里yr就一个参数代表什么?
{
if (yr.size() != bot.size())
{
cerr << "Year data, bottle data mismatch, array set to 0 size.\n";
years = 0;
data = PairArray(ArrayInt(),ArrayInt());
}
else
{
data.first() = yr;
data.second() = bot;
}
}
Wine::Wine(const char * l, const PairArray & yr_bot)
: label(l), years(yr_bot.first().size()), data(yr_bot) { }
Wine::Wine(const char * l, int y) : label(l), years(y),
data(ArrayInt(0,y),ArrayInt(0,y))
{}
void Wine::GetBottles()
{
if (years < 1)
{
cout << "No space allocated for data\n";
return;
}
cout << "Enter " << label <<
" data for " << years << " year(s):\n";
for (int i = 0; i < years; 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 < years; i++)
cout << '\t' << data.first()[i]
<< '\t' << data.second()[i] << endl;
}
//----------wine.cpp------
int main()
{
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";
return 0;
}
data的初始化传值为什么是我上面所述实在不明白,大家帮我讲解下吧,谢谢你们啊~