C++primer plus第六版课后编程练习答案14.1

#include <iostream>
#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;}
		void setmember(const T1 &t1,const T2 &t2)
		{
			a=t1;
			b=t2;
		}
		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;
}

#include <iostream>
#include <string>
#include <valarray>
#include "pair.cpp"//解决类声明和定义写在同一个cpp造成的定义冲突的方法,将所有方法写成内联方法

using namespace std;

typedef valarray<int> ArrayInt;
typedef Pair<ArrayInt,ArrayInt> PairArray;


class Wine
{
private:
	string name;
	PairArray p;
	int yearnumber;
public:
	Wine(const char *l,int y,const int yr[],const int bot[]):name(l)
	{
		yearnumber=y;
		ArrayInt f(yr,y);//构造valarray<int>数组  
		ArrayInt b(bot,y);  
		p.setmember(f,b);
	}

	Wine(const char *l,int y)
	{
		name=l;
		yearnumber=y;
		p.setmember(ArrayInt(y),ArrayInt(y)); 
	}
	
	void GetBottles()
	{
		cout<<"您能够输入"<<yearnumber<<"次年份和瓶数"<<endl;
		for(int i=0;i<yearnumber;i++)
		{
			cout<<"请输入年份:";
			cin>>p.first()[i];
			cout<<"请输入瓶数:";
			cin>>p.second()[i];
		}
	}
	
	string Label()
	{
		return name;
	}

	int sum()
	{
		return p.second().sum();
	}

	void show()
	{
		cout<<"葡萄酒名称:"<<name<<endl;
		cout<<"储存年数:"<<yearnumber<<endl;
		for(int i=0;i<yearnumber;i++)
		{
			cout<<"年份:"<<p.first()[i]<<endl;
			cout<<"瓶数:"<<p.second()[i]<<endl;
		}
	}
};

#include <iostream>
#include "wine.cpp"

using namespace std;

int main()
{
	cout<<"Eneter name of wine:";
	char lab[50];
	cin.getline(lab,50);
	cout<<"Enter number of year:";
	int yrs;
	cin>>yrs;
	Wine holding(lab,yrs);
	holding.GetBottles();
	holding.show();

//	Pair<int,int> a(1,2);
//	cout<<a.first()<<endl
//		<<a.second()<<endl;
	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;

}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值