c++ primer plus课后14_2

pair.h

template<typename T1, typename T2>
class pair
{
private:
	T1 year;
	T2 botnum;
public:
	pair();
	pair(const T1& a, const T2& b) :year(a), botnum(b){}
	T1 & first(){ return year; }
	T2 & second(){ return botnum; }
	T1 first() const { return year; }
	T2 second() const { return botnum; }
};

wine.h

#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;

class wine
{
private:
	string label;	//wine label
	int year;		//number of year
	pairArray data;		//vintage year and botnum
public:
	wine() :label("none"), year(0), data(ArrayInt(), ArrayInt()) { }
	wine(const char * l, int y, const int yr[], const int bot[]);
	wine(const char*l, int y);
	void getBottles();	
	void show() const;
	int sum() const { return data.second().sum(); }
	const string& Label(){ return label; }

};

wine::wine(const char * l, int y, const int yr[], const int bot[])
	:label(l), year(y), data(ArrayInt(yr,y), ArrayInt(bot,y))
{ 
}

wine::wine(const char*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"
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";
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值