您的位置:首页 > 编程语言 > C语言/C++

C++代码重用——包含

2016-03-18 09:50 357 查看
#ifndef PAIRS_H
#define PAIRS_H

#include <iostream>
#include <valarray>

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() {}
void Set_Pair(const T1 & aval,const T2 & bval);
void Show(int ys);
int  Sum(void);
};

template <class T1,class T2>
T1 & Pair<T1,T2>::first()
{
return a;
}

template <class T1,class T2>
T2 & Pair<T1,T2>::second()
{
return b;
}

template <class T1,class T2>
void Pair<T1,T2>::Set_Pair(const T1 & aval,const T2 & bval)
{
a=aval;
b=bval;

}

template <class T1,class T2>
void Pair<T1,T2>::Show(int ys)
{
int i=0;
for (;i<ys;i++)
{
cout <<"\t "<<a[i]<<"\t"<<b[i] <<endl;
}

}

template <class T1,class T2>
int Pair<T1,T2>::Sum(void)
{
return b.sum();
}
#endif


#ifndef WINE_H
#define WINE_H

#include <string>
#include "pairs.h"
#include <valarray>
using namespace std;

class wine
{
typedef  valarray<int> ArrayInt;
typedef  Pair<ArrayInt,ArrayInt> PairArray;
private:
string  name;
PairArray year_bottles;
int years;
public:
wine(){}
wine(const char *l,int y,const int yr[],const int bot[]);
wine(const char *l,int y);
void GetBottles(void);
void Show(void);
int sum(void);
string Label(void){return name;}
};
#endif


#include"wine.h"
#include"pairs.h"
#include<iostream>
//#include <stdlib>
#include<string>

using namespace std;

wine::wine(const char *l,int y,const int yr[],const int bot[])
{
name=*l;
years=y;
year_bottles.Set_Pair(ArrayInt(yr,y),ArrayInt(bot,y));
}
wine::wine(const char *l,int y)
{
name=*l;
years=y;
}
void wine::GetBottles(void)
{
int i=0;
ArrayInt year(years),bottle(years);
cout << "Enter "<< name <<"data for "<<years <<" year(s):" <<endl;
for(;i<years;i++)
{
cout << "Enter year: ";
cin >>year[i];
//cout << endl;
cout << "Enter bottles for that year: ";
cin >>bottle[i];
//cout << endl;
}
year_bottles.Set_Pair(year,bottle);
}
void wine::Show(void)
{

cout << "wine: "<< name <<endl;
cout <<"\t Year\t Bottles" <<endl;
year_bottles.Show(years);

}

int wine::sum(void)
{
int s=0;
s=year_bottles.Sum();
return s;
}


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

using namespace std;

int main(void)
{
cout << "Enter name of wine: ";
char lab[50];
cin.getline(lab,50);
cin.sync();
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 <<"Bey\n";
return 0;
}


wine类包含string和Pair两个类,前者用于存储酒名,后者有2个valarray<int>对象,分别用于存储酿造年份和该年的瓶数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: