1 // chapter14_1_wine.h
2
3 #ifndef LEARN_CPP_CHAPTER14_1_WINE_H
4 #define LEARN_CPP_CHAPTER14_1_WINE_H
5
6 #include <valarray>
7 #include <string>
8
9 typedef std::valarray<int> ArrayInt;
10 typedef std::pair<ArrayInt, ArrayInt> PairArray;
11
12 class Wine {
13 private:
14 std::string label;
15 int numofyears;
16 PairArray year_bots;
17 public:
18 Wine();
19 Wine(const char * l, int y, const int ye[], const int bot[]);
20 Wine(const char * l, int y);
21 ~Wine();
22 void GetBottles();
23 std::string & Label();
24 int sum() const;
25 void show() const;
26 };
27
28 #endif //LEARN_CPP_CHAPTER14_1_WINE_H
29
30
31 // chapter14_1_wine.cpp
32
33 #include "chapter14_1_wine.h"
34 #include <iostream>
35
36 Wine::Wine() {
37 label = "none";
38 numofyears = 0;
39 year_bots.first = ArrayInt(numofyears);
40 year_bots.second = ArrayInt(numofyears);
41 }
42
43 Wine::Wine(const char *l, int y, const int *ye, const int *bot) {
44 label = l;
45 numofyears = y;
46 year_bots.first = ArrayInt(numofyears);
47 year_bots.second = ArrayInt(numofyears);
48 for (int i = 0; i < numofyears; ++ i) {
49 year_bots.first[i] = ye[i];
50 year_bots.second[i] = bot[i];
51 }
52 }
53
54 Wine::Wine(const char *l, int y) {
55 label = l;
56 numofyears = y;
57 year_bots.first = ArrayInt(numofyears);
58 year_bots.second = ArrayInt(numofyears);
59 }
60
61 Wine::~Wine() {
62
63 }
64
65 void Wine::GetBottles() {
66 using namespace std;
67 for (int i = 0; i < numofyears; ++ i) {
68 cout << "#" << i << " year: ";
69 cin >> year_bots.first[i];
70 cout << "#" << i << " bottles: ";
71 cin >> year_bots.second[i];
72 }
73 cout << "finished" << endl;
74 }
75
76 std::string &Wine::Label() {
77 return label;
78 }
79
80 int Wine::sum() const {
81 return year_bots.second.sum();
82 }
83
84 void Wine::show() const {
85 using namespace std;
86 cout << "year bottles" << endl;
87 for (int i = 0; i < numofyears; ++ i)
88 cout << year_bots.first[i] << " " << year_bots.second[i] << endl;
89 }
90
91
92 // run
93
94 void ch14_1() {
95 using namespace std;
96 cout << "enter name of wine: ";
97 char lab[50];
98 cin.getline(lab, 50);
99 cout << "enter number of years: ";
100 int yrs;
101 cin >> yrs;
102
103 Wine holding(lab, yrs);
104 holding.GetBottles();
105 holding.show();
106
107 const int YRS = 3;
108 int y[YRS] = {1993, 1995, 1998};
109 int b[YRS] = {48, 60, 72};
110 Wine more("Gushing Grape Red", YRS, y, b);
111 more.show();
112 cout << "total bottles for " << more.Label() << ": " << more.sum() << endl;
113 cout << "bye" << endl;
114 return;
115 }
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 »
编程练习答案——第14章