头文件1
#pragma once
#ifndef PAIR_H_
#define PAIR_H_
template <class T1,class T2>
class Pair {
private:
T1 a;
T2 b;
public:
T1& first() { return a; }
T2& secend() { return b; }
T1 first() const { return a; }
T2 secend() const { return b; }
Pair(const T1 &aval,const T2 &bval):a(aval),b(bval) { }
Pair(){ }
};
#endif
头文件2:
#pragma once
#include<string>
#include<valarray>
#include"Pair.h"
#ifndef WINE2_H_
#define WINE2_H_
class Wine {
private:
typedef std::valarray<int> ArrayInt;
typedef Pair<ArrayInt, ArrayInt> PairArray;
PairArray data;
int num_years;
std::string label;
public:
Wine():label("none"),num_years(0),data(ArrayInt(),ArrayInt()){ }
Wine(const char* l, int y, const int yr[], const int bot[]);
Wine(const char* l, int y);
Wine(const char* l, const PairArray& d);
Wine(const char* l, int y,const ArrayInt& a, const ArrayInt& b);
void Getbottles();
std::string& Label() { return label; }
int sum() { return data.secend().sum(); }
void show() const;
};
#endif
头文件2中相关函数的定义文件:
#include<iostream>
#include"wine2.h"
using std::cout;
using std::cin;
using std::endl;
using std::cerr;
Wine::Wine(const char* l, int y, const int yr[], const int bot[]):label(l),num_years(y),
data(ArrayInt(yr, y), ArrayInt(bot, y)) { }
Wine::Wine(const char* l, int y):label(l),num_years(y),data(ArrayInt(0,y),ArrayInt(0,y)){ }
Wine::Wine(const char* l, const PairArray& d) : label(l), num_years(data.first().size()), data(d) { }
Wine::Wine(const char* l, int y,const ArrayInt& a,const ArrayInt& b):label(l),num_years(y),data(ArrayInt(a),ArrayInt(b) ){
if (a.size() != b.size()) {
cerr << "年数与瓶数不相等,故数组的长度设为0!" << endl;
num_years = 0;
data=PairArray(ArrayInt(), ArrayInt());
}
else {
data.first() = a;
data.secend() = b;
}
}
void Wine::Getbottles() {
if (num_years < 1) {
cout << "没有为这种类型的年数分配存储空间!" << endl;
return;
}
else {
cout << "请输入" << label << "关于" << num_years << "个年数的数据:" << endl;
for (int i = 0; i < num_years; i++) {
cout << "请输入年份:";
cin >> data.first()[i];
cout << "请输入那年的瓶数:";
cin >> data.secend()[i];
}
}
}
void Wine::show() const{
cout << "Wine:" << label << endl;
cout << "\t年数\t瓶数" << endl;
for (int i = 0; i < num_years; i++) {
cout << "\t" << data.first()[i]
<< "\t" << data.secend()[i] << endl;
}
}
主程序文件:
#include<iostream>
#include"wine2.h"
int main() {
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);
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;
}
运行结果: