第十四章编程练习(1)

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值