实验4 类的组合、继承、模板类、标准库

1. 实验任务1
task1_1.cpp
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A {
 5 public:
 6     A(int x0, int y0);
 7     void display()const;
 8 private:
 9     int x, y;
10 };
11 A::A(int x0,int y0):x{x0},y{y0}{}
12 void A::display()const {
13     cout << x << "," << y << endl;
14 }
15 
16 class B {
17 public:
18     B(double x0, double y0);
19     void diaplay()const;
20 private:
21     double x, y;
22 };
23 B::B(double x0, double y0) :x{ x0 }, y{ y0 } {}
24 void B::diaplay()const {
25     cout << x << "," << y << endl;
26 }
27 void test() {
28     cout << "测试类A:" << endl;
29     A a(3, 4);
30     a.display();
31     cout << "测试类B:" << endl;
32     B b(3.2, 5.6);
33     b.diaplay();
34 }
35 int main() {
36     test();
37 }
View Code

task1_2.cpp
 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 template<typename T>
 6 class X {
 7 public:
 8     X(T x0, T y0);
 9     void display();
10 private:
11     T x, y;
12 };
13 template <typename T>
14 X<T>::X(T x0, T y0) :x{ x0 }, y{ y0 } {}
15 
16 template <typename T>
17 void X<T>::display() {
18     cout << x << ", " << y << endl;
19 }
20 
21 
22 void test() {
23     cout << "测试1: 类模板X中的抽象类型T用int实例化" << endl;
24     X<int> x1(3, 4);
25     x1.display();
26     cout << endl;
27     cout << "测试2: 类模板X中的抽象类型T用double实例化" << endl;
28     X<double> x2(3.2, 5.6);
29     x2.display();
30     cout << endl;
31     cout << "测试3: 类模板X中的抽象类型T用string实例化" << endl;
32     X<string> x3("hello", "oop");
33     x3.display();
34 }
35 int main() {
36     test();
37 }
View Code

 

2. 实验任务2
GradeCalc.hpp
  1 #include<iostream>
  2 #include<vector>
  3 #include<string>
  4 #include<algorithm>
  5 #include<numeric>
  6 #include<iomanip>
  7 
  8 using std::vector;
  9 using std::string;
 10 using std::cin;
 11 using std::cout;
 12 using std::endl;
 13 
 14 class GradeCalc :public vector<int> {
 15 public:
 16     GradeCalc(const string& cname, int size);
 17     void input();
 18     void output() const;
 19     void sort(bool ascending = false);
 20     int min()const;
 21     int max()const;
 22     float average()const;
 23     void info();
 24 private:
 25     void compute();//成绩统计
 26 
 27 private:
 28     string course_name;
 29     int n;
 30     vector<int>counts = vector<int>(5, 0);// 保存各分数段人数([0,60), [60, 70), [70, 80), [80, 90), [90, 100]
 31     vector<double> rates = vector<double>(5, 0); // 保存各分数段比例
 32 };
 33 GradeCalc::GradeCalc(const string &cname,int size):course_name{cname},n{size}{}
 34 
 35 void GradeCalc::input() {
 36     int grade;
 37 
 38     for (int i = 0; i < n; i++) {
 39         cin >> grade;
 40         this->push_back(grade);
 41     }
 42 }
 43 
 44 void GradeCalc::output()const {
 45     for (auto ptr = this->begin(); ptr != this->end(); ptr++)
 46         cout << *ptr << " ";
 47     cout << endl;
 48 }
 49 
 50 void GradeCalc::sort(bool ascending) {
 51     if (ascending)
 52         std::sort(this->begin(), this->end());
 53     else
 54         std::sort(this->begin(), this->end(), std::greater<int>());
 55 }
 56 
 57 int GradeCalc::min()const {
 58     return *std::min_element(this->begin(), this->end());
 59 }
 60 
 61 int GradeCalc::max()const {
 62     return *std::max_element(this->begin(), this->end());
 63 }
 64 
 65 float GradeCalc::average()const {
 66     return std::accumulate(this->begin(), this->end(), 0) * 1.0 / n;
 67 }
 68 
 69 void GradeCalc::compute() {
 70     for (int grade : *this) {
 71         if (grade < 60)
 72             counts.at(0)++;
 73         else if (grade >= 60 && grade < 70)
 74             counts.at(1)++;
 75         else if (grade >= 70 && grade < 80)
 76             counts.at(2)++;
 77         else if (grade >= 80 && grade < 90)
 78             counts.at(3)++;
 79         else if (grade >= 90)
 80             counts.at(4)++;
 81     }
 82     for (int i = 0; i < rates.size(); ++i)
 83         rates.at(i) = counts.at(i) * 1.0 / n;
 84 }
 85 
 86 void GradeCalc::info() {
 87     cout << "课程名称:\t" << course_name << endl;
 88     cout << "排序后成绩: \t";
 89     sort(); output();
 90     cout << "最高分:\t" << max() << endl;
 91     cout << "最低分:\t" << min() << endl;
 92     cout << "平均分:\t" << std::fixed << std::setprecision(2) <<
 93         average() << endl;
 94     compute(); // 统计各分数段人数、比例
 95     vector<string> tmp{ "[0, 60) ", "[60, 70)", "[70, 80)","[80, 90)",
 96     "[90, 100]" };
 97     for (int i = tmp.size() - 1; i >= 0; --i)
 98         cout << tmp[i] << "\t: " << counts[i] << "人\t"
 99         << std::fixed << std::setprecision(2) << rates[i] * 100 <<
100         "%" << endl;
101 }
View Code
task2.cpp
 1 #include"GradeCalc.hpp"
 2 #include<iomanip>
 3 
 4 void test() {
 5     int n;
 6     cout << "输入班级人数:";
 7     cin >> n;
 8 
 9     GradeCalc c1("oop", n);
10 
11     cout << "录入成绩: " << endl;;
12     c1.input();
13     cout << "输出成绩: " << endl;
14     c1.output();
15 
16     cout<<string (20,'*')+"课程成绩信息" + string(20, '*') << endl;
17     c1.info();
18 }
19 int main() {
20     test();
21 }
View Code

问题1:派生类GradeCalc定义中,成绩存储在哪里?派生类方法sort, min, max, average,
output都要访问成绩,是通过什么接口访问到每个成绩的?input方法是通过什么接口实现数
据存入对象的?
 成绩存储在从基类继承过来的vector<int>数组中;通过this的迭代器接口;通过this的迭代器接口;
问题2:代码line68分母的功能是?去掉乘以1.0代码,重新编译、运行,结果有影响吗?为什
么要乘以1.0?
总和除以人数求平均值;可正常编译运行,但会导致结果无法出现小数;乘以1.0使结果可以出现小数;
问题3:从真实应用场景角度考虑,GradeCalc类在设计及代码实现细节上,有哪些地方尚未
考虑周全,仍需继续迭代、完善?
添加及格率和优秀率等结果;
3. 实验任务3
GradeCalc.hpp
 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 #include <algorithm>
 5 #include <numeric>
 6 #include <iomanip>
 7 using std::vector;
 8 using std::string;
 9 using std::cin;
10 using std::cout;
11 using std::endl;
12 class GradeCalc {
13 public:
14     GradeCalc(const string& cname, int size);
15     void input(); // 录入成绩
16     void output() const; // 输出成绩
17     void sort(bool ascending = false); // 排序 (默认降序)
18     int min() const; // 返回最低分
19     int max() const; // 返回最高分
20     float average() const; // 返回平均分
21     void info(); // 输出课程成绩信息
22 private:
23     void compute(); // 成绩统计
24 private:
25     string course_name; // 课程名
26     int n; // 课程人数
27     vector<int> grades; // 课程成绩
28     vector<int> counts = vector<int>(5, 0); // 保存各分数段人数([0,60), [60, 70), [70, 80), [80, 90), [90, 100]
29         vector<double> rates = vector<double>(5, 0); // 保存各分数段比例
30 };
31 GradeCalc::GradeCalc(const string& cname, int size) :
32     course_name{ cname }, n{ size } {}
33 void GradeCalc::input() {
34     int grade;
35     for (int i = 0; i < n; ++i) {
36         cin >> grade;
37         grades.push_back(grade);
38     }
39 }
40 void GradeCalc::output() const {
41     for (int grade : grades)
42         cout << grade << " ";
43     cout << endl;
44 }
45 void GradeCalc::sort(bool ascending) {
46     if (ascending)
47         std::sort(grades.begin(), grades.end());
48     else
49         std::sort(grades.begin(), grades.end(), std::greater<int>());
50 }
51 int GradeCalc::min() const {
52     return *std::min_element(grades.begin(), grades.end());
53 }
54 int GradeCalc::max() const {
55     return *std::max_element(grades.begin(), grades.end());
56 }
57 float GradeCalc::average() const {
58     return std::accumulate(grades.begin(), grades.end(), 0) * 1.0 / n;
59 }
60 void GradeCalc::compute() {
61     for (int grade : grades) {
62         if (grade < 60)
63             counts.at(0)++;
64         else if (grade >= 60 && grade < 70)
65             counts.at(1)++;
66         else if (grade >= 70 && grade < 80)
67             counts.at(2)++;
68         else if (grade >= 80 && grade < 90)
69             counts.at(3)++;
70         else if (grade >= 90)
71             counts.at(4)++;
72     }
73     for (int i = 0; i < rates.size(); ++i)
74         rates.at(i) = counts.at(i) * 1.0 / n;
75 }
76 void GradeCalc::info() {
77     cout << "课程名称:\t" << course_name << endl;
78     cout << "排序后成绩: \t";
79     sort(); output();
80     cout << "最高分:\t" << max() << endl;
81     cout << "最低分:\t" << min() << endl;
82     cout << "平均分:\t" << std::fixed << std::setprecision(2) <<average() << endl;
83     compute(); // 统计各分数段人数、比例
84     vector<string> tmp{ "[0, 60) ", "[60, 70)", "[70, 80)","[80, 90)","[90, 100]" };
85     for (int i = tmp.size() - 1; i >= 0; --i)
86         cout << tmp[i] << "\t: " << counts[i] << "人\t"
87         << std::fixed << std::setprecision(2) << rates[i] * 100 <<"%" << endl;
88 }
View Code
task3.cpp
 1 #include "GradeCalc.hpp"
 2 #include <iomanip>
 3 void test() {
 4     int n;
 5     cout << "输入班级人数: ";
 6     cin >> n;
 7     GradeCalc c1("OOP", n);
 8     cout << "录入成绩: " << endl;;
 9     c1.input();
10     cout << "输出成绩: " << endl;
11     c1.output();
12     cout << string(20, '*') + "课程成绩信息" + string(20, '*') << endl;
13     c1.info();
14 }
15 int main() {
16     test();
17 }
View Code

问题1:组合类GradeCalc定义中,成绩存储在哪里?组合类方法sort, min, max, average,
output都要访问成绩,是通过什么接口访问到每个成绩的?观察与实验任务2在代码写法细节
上的差别。
储存在类中的一个private成员vector<int> grades中;通过grades.访问;类中多了一个grades成员,函数的实现上用grades.代替this->;
问题2:对比实验任务2和实验任务3,主体代码逻辑(测试代码)没有变更,类GradeCalc的
接口也没变,变化的是类GradeCalc的设计及接口内部实现细节。你对面向对象编程有什么新
的理解和领悟吗?
确认了接口后,就可以通过仅改变类的设计和接口内部的实现来修改程序
4. 实验任务4
 task4_1
 1 #include<iostream>
 2 #include<string>
 3 #include<limits>
 4 
 5 using namespace std;
 6 
 7 void test1() {
 8     string s1, s2;
 9     cin >> s1 >> s2;
10     cout << "s1:" << s1 << endl;// cin: 从输入流读取字符串, 碰到空白符(空格/回车/Tab)即结束
11     cout << "s2:" << s2 << endl;
12 
13 }
14 
15 void test2() {
16     string s1, s2;
17     getline(cin, s1);
18     getline(cin, s2);
19     cout << "s1:" << s1 << endl;// getline(): 从输入流中提取字符串,直到遇到换行符
20     cout << "s2:" << s2 << endl;
21 }
22 
23 void test3() {
24     string s1, s2;
25     getline(cin, s1, ' ');//从输入流中提取字符串,直到遇到指定分隔符
26     getline(cin, s2);
27     cout << "s1: " << s1 << endl;
28     cout << "s2: " << s2 << endl;
29 
30 }
31 
32 int main() {
33     cout << "测试1: 使用标准输入流对象cin输入字符串" << endl;
34     test1();
35     cout << endl;
36 
37     cin.ignore(numeric_limits<streamsize>::max(), '\n');
38 
39     cout << "测试2: 使用函数getline()输入字符串" << endl;
40     test2();
41     cout << endl;
42     cout << "测试3: 使用函数getline()输入字符串, 指定字符串分隔符" << endl;
43     test3();
44 }
View Code

问题1:去掉task4_1.cpp的line35,重新编译、运行,给出此时运行结果截图。查阅资料,回答
line35在这里的用途是什么?
持续忽略字符直到\n出现。有时,输入一些数据后,输入流会残余一些不需要的字符,如果不清理这些字符,下一次cin可能会输入无用字符导致结果错误。
 
task4_2.cpp
 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 #include<limits>
 5 using namespace std;
 6 void output(const vector<string>& v) {
 7     for (auto& s : v)
 8         cout << s << endl;
 9 }
10 
11 void test() {
12     int n;
13     while (cout << "Enter n: ", cin >> n) {
14         vector<string>v1;
15 
16         for (int i = 0; i < n; i++) {
17             string s;
18             cin >> s;
19             v1.push_back(s);
20         }
21 
22         cout << "output v1: " << endl;
23         output(v1);
24         cout << endl;
25     }
26 }
27 int main() {
28     cout << "测试: 使用cin多组输入字符串" << endl;
29     test();
30 }
View Code

task4_3.cpp
 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 #include<limits>
 5 
 6 using namespace std;
 7 
 8 void output(const vector<string> &v) {
 9     for (auto& s : v)
10         cout << s << endl;
11 }
12 
13 void test() {
14     int n;
15     while (cout << "Enter n: ", cin >> n) {
16         cin.ignore(numeric_limits<streamsize>::max(), '\n');
17 
18         vector<string>v2;
19 
20         for (int i = 0; i < n; i++) {
21             string s;
22             getline(cin, s);
23             v2.push_back(s);
24         }
25         cout << "output v2: " << endl;
26         output(v2);
27         cout << endl;
28     }
29 }
30 int main() {
31     cout << "测试: 使用函数getline()多组输入字符串" << endl;
32     test();
33 }
View Code

 

问题2:去掉task4_3.cpp的line16,重新编译、运行,给出此时运行结果。查阅资料,回答line16
在这里的用途是什么?
持续忽略字符直到\n出现。有时,输入一些数据后,输入流会残余一些不需要的字符,如果不清理这些字符,下一次cin可能会输入无用字符导致结果错误。
这里起到了清理cin<<n后‘ ’的作用

 task5

grm.hpp
 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 template<typename T>
 6 class GameResourceManager {
 7 public:
 8     GameResourceManager(T x0);
 9     T get();
10     void update(T x1);
11 
12 private:
13     T x;
14 
15 };
16 
17 template<typename T>
18 GameResourceManager<T>::GameResourceManager(T x0) :x{ x0 } {}
19 
20 template<typename T>
21 T GameResourceManager<T>::get() {
22     if (x < 0)return 0;
23     else return x;
24 }
25 
26 template<typename T>
27 void GameResourceManager<T>::update(T x1) {
28     x += x1;
29 }
View Code

task5.cpp

 1 #include "grm.hpp"
 2 #include <iostream>
 3 using std::cout;
 4 using std::endl;
 5 void test1() {
 6     GameResourceManager<float> HP_manager(99.99);
 7     cout << "当前生命值: " << HP_manager.get() << endl;
 8     HP_manager.update(9.99);
 9     cout << "增加9.99生命值后, 当前生命值: " << HP_manager.get() << endl;
10     HP_manager.update(-999.99);
11     cout << "减少999.99生命值后, 当前生命值: " << HP_manager.get() << endl;
12 }
13 void test2() {
14     GameResourceManager<int> Gold_manager(100);
15     cout << "当前金币数量: " << Gold_manager.get() << endl;
16     Gold_manager.update(50);
17     cout << "增加50个金币后, 当前金币数量: " << Gold_manager.get() << endl;
18     Gold_manager.update(-99);
19     cout << "减少99个金币后, 当前金币数量: " << Gold_manager.get() << endl;
20 }
21 int main() {
22     cout << "测试1: 用float类型对类模板GameResourceManager实例化" << endl;
23     test1();
24     cout << endl;
25     cout << "测试2: 用int类型对类模板GameResourceManager实例化" << endl;
26     test2();
27 }
View Code

 task6

info.hpp

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 using namespace std;
 5 
 6 class Info {
 7 public:
 8     Info(string nick, string con,string c,int n):nickname{nick},contact{con},city{c},num{n}{}
 9     void display()const {
10         cout << "nickname:" <<"\t: "<< nickname << endl << "contact:" << "\t: "<<contact << endl << "city:" <<"\t: "<< city << endl << "num" << "\t: "<<num << endl;
11     }
12 private:
13     string nickname;
14     string contact;
15     string city;
16     int num;
17 
18 };
View Code

 

task6.cpp

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 #include "info.hpp"
 5 
 6 using namespace std;
 7 
 8 const int capacity = 100;
 9 vector<Info>audience_lst;
10 
11 
12 int main() {
13     int current_capacity = capacity;  // 当前剩余的座位数
14 
15     while (true) {
16 
17         string nickname, contact, city;
18         int n;
19 
20         // 输入信息
21         cout << "请输入昵称: ";
22         getline(cin, nickname);
23         if (nickname.empty()) break;  // 如果输入为空,退出
24 
25         cout << "请输入联系方式 (Email 或 手机号): ";
26         getline(cin, contact);
27 
28         cout << "请输入所在城市: ";
29         getline(cin, city);
30 
31         cout << "请输入预定参加人数: ";
32         cin >> n;
33         cin.ignore();  // 忽略换行符,防止影响下一次输入
34 
35         // 检查预定人数是否超出剩余容量
36         if (n > current_capacity) {
37             cout << "只剩下 " << current_capacity << "个名额了。 " << endl << "1.输入u,更新信息" << endl << "2.输入q,退出预定" << endl;
38             char choice;
39             cin >> choice;
40             cin.ignore(numeric_limits<streamsize>::max(), '\n');
41 
42             if (choice == 'q') {
43                 break;  // 退出
44             }
45             else if (choice == 'u') {
46                 // 更新信息
47                 cout << "请输入新的预定人数: ";
48                 cin >> n;
49                 cin.ignore(numeric_limits<streamsize>::max(), '\n');
50                 if (n > current_capacity) {
51                     cout << "预定人数依然超出剩余容量 " << current_capacity << endl;
52                     continue;
53                 }
54             }
55         }
56 
57         // 如果预约成功,添加到 audience_lst 中
58         audience_lst.push_back(Info(nickname, contact, city, n));
59         current_capacity -= n;
60 
61         // 如果已经预约满额,提示用户并退出
62         if (current_capacity <= 0) {
63             cout << "预约已满,无法继续预约!\n";
64             break;
65         }
66     }
67     // 显示所有预约的听众信息
68     cout << "截至目前共有" << 100 - current_capacity << "位听众预约。预约听众信息如下:" << endl << string(20, '*') << endl;
69     for (const auto& audience : audience_lst) {
70         audience.display();
71         cout << string(20, '*') << endl;
72     }
73     return 0;
74 }
View Code

 task7

date.h

 1 #pragma once
 2 #ifndef  DATE H
 3 #define  DATE H
 4 class Date {
 5 private:
 6     int year;
 7     int month;
 8     int day;
 9     int totalDays;
10 public:
11     Date(int year, int month, int day);
12     int getYear()const { return year; }
13     int getMonth()const { return month; }
14     int getDay()const { return day; }
15     int getMaxDay()const;
16     bool isLeapYear()const {
17         return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
18     }
19     void show()const;
20     int distance(const Date& date)const {
21         return totalDays - date.totalDays;
22     }
23 };
24 #endif//  DATE H
View Code

accumulator.h

 1 #pragma once
 2 #ifndef  ACCUMULATOR H
 3 #define  ACCUMULATOR H
 4 #include"date.h"
 5 class Accumulator {
 6 private:
 7     Date lastDate;
 8     double value;
 9     double sum;
10 public:
11     Accumulator(const Date& date, double value) :lastDate(date), value(value), sum{ 0 } {
12     }
13 
14     double getSum(const Date& date)const {
15         return sum + value * date.distance(lastDate);
16     }
17 
18     void change(const Date& date, double value) {
19         sum = getSum(date);
20         lastDate = date; this->value = value;
21     }
22 
23     void reset(const Date& date, double value) {
24         lastDate = date; this->value = value; sum = 0;
25     }
26 };
27 #endif//ACCUMULATOR H
View Code

date.cpp

 1 #include"date.h"
 2 #include<iostream>
 3 #include<cstdlib>
 4 using namespace std;
 5 namespace {
 6     const int DAYS_BEFORE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 };
 7 }
 8 Date::Date(int year, int month, int day) :year{ year }, month{ month }, day{ day } {
 9     if (day <= 0 || day > getMaxDay()) {
10         cout << "Invalid date:";
11         show();
12         cout << endl;
13         exit(1);
14     }
15     int years = year - 1;
16     totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day;
17     if (isLeapYear() && month > 2)totalDays++;
18 }
19 int Date::getMaxDay()const {
20     if (isLeapYear() && month == 2)
21         return 29;
22     else return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
23 }
24 
25 void Date::show()const {
26     cout << getYear() << "-" << getMonth() << "-" << getDay();
27 }
View Code

account.h

 1 #pragma once
 2 #ifndef  ACCOUNT H
 3 #define  ACCOUNT H
 4 #include"date.h"
 5 #include"accumulator.h"
 6 #include<string>
 7 class Account {
 8 private:
 9     std::string id;
10     double balance;
11     static double total;
12 protected:
13     Account(const Date& date, const std::string& id);
14     void record(const Date& date, double amount, const std::string& desc);
15     void error(const std::string& msg)const;
16 public:
17     const std::string& getId()const { return id; }
18     double getBalance()const { return balance; }
19     static double getTotal() { return total; }
20 
21     void show()const;
22 };
23 class SavingsAccount :public Account {
24 private:
25     Accumulator acc;
26     double rate;
27 public:
28     SavingsAccount(const Date& date, const std::string& id, double rate);
29     double getRate()const { return rate; }
30 
31     void deposit(const Date& date, double amount, const std::string& desc);
32     void withdraw(const Date& date, double amount, const std::string& desc);
33     void settle(const Date& date);
34 };
35 class CreditAccount :public Account {
36 private:
37     Accumulator acc;
38     double credit;
39     double rate;
40     double fee;
41     double getDebt()const {
42         double balance = getBalance();
43         return (balance < 0 ? balance : 0);
44     }
45 public:
46     CreditAccount(const Date& date, const std::string& id, double credit, double rate, double fee);
47     double getCredit()const { return credit; }
48     double getRate()const { return rate; }
49     double getAvailableCredit()const {
50         if (getBalance() < 0)
51             return credit + getBalance();
52         else
53             return credit;
54     }
55     void deposit(const Date& date, double amount, const std::string& desc);
56     void withdraw(const Date& date, double amount, const std::string& desc);
57     void settle(const Date& date);
58     void show()const;
59 };
60 #endif//ACCOUNT H
View Code

account.cpp

 1 #include"account.h"
 2 #include<cmath>
 3 #include<iostream>
 4 using namespace std;
 5 double Account::total = 0;
 6 
 7 Account::Account(const Date& date, const string& id) :id{ id }, balance{ 0 } {
 8     date.show(); cout << "\t#" << id << "created" << endl;
 9 }
10 
11 
12 void Account::record(const Date& date, double amount, const string& desc) {
13     amount = floor(amount * 100 + 0.5) / 100;
14     balance += amount;
15     total += amount;
16     date.show();
17     cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
18 }
19 
20 void Account::show()const { cout << id << "\tBalance:" << balance; }
21 void Account::error(const string& msg)const {
22     cout << "Error(#" << id << "):" << msg << endl;
23 }
24 
25 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) :Account(date, id), rate(rate), acc(date, 0) {}
26 
27 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) {
28     record(date, amount, desc);
29     acc.change(date, getBalance());
30 }
31 
32 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) {
33     if (amount > getBalance()) {
34         error("not enough money");
35     }
36     else {
37         record(date, -amount, desc);
38         acc.change(date, getBalance());
39     }
40 }
41 
42 void SavingsAccount::settle(const Date& date) {
43     double interest = acc.getSum(date) * rate / date.distance(Date(date.getYear() - 1, 1, 1));
44     if (interest != 0)record(date, interest, "interest");
45     acc.reset(date, getBalance());
46 }
47 
48 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee) :Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) {}
49 
50 void CreditAccount::deposit(const Date& date, double amount, const string& desc) {
51     record(date, amount, desc);
52     acc.change(date, getDebt());
53 }
54 
55 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) {
56     if (amount - getBalance() > credit) {
57         error("not enough credit");
58     }
59     else {
60         record(date, -amount, desc);
61         acc.change(date, getDebt());
62     }
63 }
64 
65 void CreditAccount::settle(const Date& date) {
66     double interest = acc.getSum(date) * rate;
67     if (interest != 0)record(date, interest, "interest");
68     if (date.getMonth() == 1)
69         record(date, -fee, "annual fee");
70     acc.reset(date, getDebt());
71 }
72 
73 void CreditAccount::show()const {
74     Account::show();
75     cout << "\tAvailable credit:" << getAvailableCredit();
76 }
View Code

task7.cpp

 1 #include"account.h"
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 int main() {
 7     Date date(2008, 11, 1);
 8     SavingsAccount sa1(date, "S3755217", 0.015);
 9     SavingsAccount sa2(date, "02342342", 0.015);
10     CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
11 
12     sa1.deposit(Date(2008, 11, 5), 5000, "salary");
13     ca.withdraw(Date(2008, 11, 15), 2000, "buy a cell");
14     sa2.deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
15 
16     ca.settle(Date(2008, 12, 1));
17 
18     ca.deposit(Date(2008, 12, 1), 2016, "repay the credit");
19     sa1.deposit(Date(2008, 12, 5), 5500, "salary");
20 
21     sa1.settle(Date(2009, 1, 1));
22     sa2.settle(Date(2009, 1, 1));
23     ca.settle(Date(2009, 1, 1));
24 
25     cout << endl;
26     sa1.show(); cout << endl;
27     sa2.show(); cout << endl;
28     ca.show(); cout << endl;
29     cout << "Total:" << Account::getTotal() << endl;
30     return 0;
31 }
View Code

定义account基类,继承得到了两个派生类SavingAccounts和CreditAccounts.

 

 

posted @ 2024-11-21 22:57  Mikuuuu  阅读(12)  评论(0编辑  收藏  举报