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

任务2

源码:

  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 
 25 private:
 26     void compute();     // 成绩统计
 27 
 28 private:
 29     string course_name;     // 课程名
 30     int n;                  // 课程人数
 31     vector<int> counts = vector<int>(5, 0);      // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100]
 32     vector<double> rates = vector<double>(5, 0); // 保存各分数段比例 
 33 };
 34 
 35 GradeCalc::GradeCalc(const string &cname, int size): course_name{cname}, n{size} {}   
 36 
 37 void GradeCalc::input() {
 38     int grade;
 39 
 40     for(int i = 0; i < n; ++i) {
 41         cin >> grade;
 42         this->push_back(grade);
 43     } 
 44 }  
 45 
 46 void GradeCalc::output() const {
 47     for(auto ptr = this->begin(); ptr != this->end(); ++ptr)
 48         cout << *ptr << " ";
 49     cout << endl;
 50 } 
 51 
 52 void GradeCalc::sort(bool ascending) {
 53     if(ascending)
 54         std::sort(this->begin(), this->end());
 55     else
 56         std::sort(this->begin(), this->end(), std::greater<int>());
 57 }  
 58 
 59 int GradeCalc::min() const {
 60     return *std::min_element(this->begin(), this->end());
 61 }  
 62 
 63 int GradeCalc::max() const {
 64     return *std::max_element(this->begin(), this->end());
 65 }    
 66 
 67 float GradeCalc::average() const {
 68     return std::accumulate(this->begin(), this->end(), 0) * 1.0 / n;
 69 }   
 70 
 71 void GradeCalc::compute() {
 72     for(int grade: *this) {
 73         if(grade < 60)
 74             counts.at(0)++;
 75         else if(grade >= 60 && grade < 70)
 76             counts.at(1)++;
 77         else if(grade >= 70 && grade < 80)
 78             counts.at(2)++;
 79         else if(grade >= 80 && grade < 90)
 80             counts.at(3)++;
 81         else if(grade >= 90)
 82             counts.at(4)++;
 83     }
 84 
 85     for(int i = 0; i < rates.size(); ++i)
 86         rates.at(i) = counts.at(i) * 1.0 / n;
 87 }
 88 
 89 void GradeCalc::info()  {
 90     cout << "课程名称:\t" << course_name << endl;
 91     cout << "排序后成绩: \t";
 92     sort();  output();
 93     cout << "最高分:\t" << max() << endl;
 94     cout << "最低分:\t" << min() << endl;
 95     cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl;
 96     
 97     compute();  // 统计各分数段人数、比例
 98 
 99     vector<string> tmp{"[0, 60)  ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"};
100     for(int i = tmp.size()-1; i >= 0; --i)
101         cout << tmp[i] << "\t: " << counts[i] << "人\t" 
102              << std::fixed << std::setprecision(2) << rates[i]*100 << "%" << endl; 
103 }
GradeCalc.hpp
 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 
20 int main() {
21     test();
22 }
task2.cpp

 

运行测试截图:

 

问题:

1.派生类GradeCalc定义中,成绩存储在vector<int>容器中;派生类方法sort, min, max, average,output通过vector<int>的成员函数begin(),end()访问到每个成绩;input方法通过vector<int>的成员函数push_back()接口实现数据存入对象

2.代码line68分母的功能是将成绩的总和除以人数获取平均分;去掉乘以1.0代码,重新编译、运行,结果将变为整数,精度下降;乘以1.0将平均分结果转换为小数,更加准确

3.程序没有对输入的数据进行合法性检验,无法处理异常输入数据;程序结果无法保留下来反复查看

 

 

任务3

源码:

  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 {
 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 
 25 private:
 26     void compute();     // 成绩统计
 27 
 28 private:
 29     string course_name;     // 课程名
 30     int n;                  // 课程人数
 31     vector<int> grades;     // 课程成绩
 32     vector<int> counts = vector<int>(5, 0);      // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100]
 33     vector<double> rates = vector<double>(5, 0); // 保存各分数段比例 
 34 };
 35 
 36 GradeCalc::GradeCalc(const string &cname, int size): course_name{cname}, n{size} {}   
 37 
 38 void GradeCalc::input() {
 39     int grade;
 40 
 41     for(int i = 0; i < n; ++i) {
 42         cin >> grade;
 43         grades.push_back(grade);
 44     } 
 45 }  
 46 
 47 void GradeCalc::output() const {
 48     for(int grade: grades)
 49         cout << grade << " ";
 50     cout << endl;
 51 } 
 52 
 53 void GradeCalc::sort(bool ascending) {
 54     if(ascending)
 55         std::sort(grades.begin(), grades.end());
 56     else
 57         std::sort(grades.begin(), grades.end(), std::greater<int>());
 58         
 59 }  
 60 
 61 int GradeCalc::min() const {
 62     return *std::min_element(grades.begin(), grades.end());
 63 }  
 64 
 65 int GradeCalc::max() const {
 66     return *std::max_element(grades.begin(), grades.end());
 67 }    
 68 
 69 float GradeCalc::average() const {
 70     return std::accumulate(grades.begin(), grades.end(), 0) * 1.0 / n;
 71 }   
 72 
 73 void GradeCalc::compute() {
 74     for(int grade: grades) {
 75         if(grade < 60)
 76             counts.at(0)++;
 77         else if(grade >= 60 && grade < 70)
 78             counts.at(1)++;
 79         else if(grade >= 70 && grade < 80)
 80             counts.at(2)++;
 81         else if(grade >= 80 && grade < 90)
 82             counts.at(3)++;
 83         else if(grade >= 90)
 84             counts.at(4)++;
 85     }
 86 
 87     for(int i = 0; i < rates.size(); ++i)
 88         rates.at(i) = counts.at(i) *1.0 / n;
 89 }
 90 
 91 void GradeCalc::info()  {
 92     cout << "课程名称:\t" << course_name << endl;
 93     cout << "排序后成绩: \t";
 94     sort();  output();
 95     cout << "最高分:\t" << max() << endl;
 96     cout << "最低分:\t" << min() << endl;
 97     cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl;
 98     
 99     compute();  // 统计各分数段人数、比例
100 
101     vector<string> tmp{"[0, 60)  ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"};
102     for(int i = tmp.size()-1; i >= 0; --i)
103         cout << tmp[i] << "\t: " << counts[i] << "人\t" 
104              << std::fixed << std::setprecision(2) << rates[i]*100 << "%" << endl; 
105 }
GradeCalc.hpp
 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 
20 int main() {
21     test();
22 }
task3.cpp

 

运行测试截图:

 

问题:

1.组合类GradeCalc定义中,成绩存储内嵌对象vector<int> grades中;组合类方法sort, min, max, average,output通过vector<int>的成员函数begin(),end()访问到每个成绩;与实验任务2在代码写法上的差别主要为在类GradeCalc内通过定义的内嵌对象vector<int> grades来存储成绩,并对它进行求值等操作

2.当两个类存在一定关系,有时可以将它们设计为组合类,有时候可以将它们设计为派生类和基类,有时候两种设计方法都可以,但在类似于本次实验当中的任务中,派生类更加适用,因为使用派生类无需在设计派生类的过程中再创建内嵌对象,而是直接调用基类的成员函数

 

 

任务4

(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;  // cin: 从输入流读取字符串, 碰到空白符(空格/回车/Tab)即结束
10     cout << "s1: " << s1 << endl;
11     cout << "s2: " << s2 << endl;
12 }
13 
14 void test2() {
15     string s1, s2;
16     getline(cin, s1);  // getline(): 从输入流中提取字符串,直到遇到换行符
17     getline(cin, s2);
18     cout << "s1: " << s1 << endl;
19     cout << "s2: " << s2 << endl;
20 }
21 
22 void test3() {
23     string s1, s2;
24     getline(cin, s1, ' '); //从输入流中提取字符串,直到遇到指定分隔符
25     getline(cin, s2);
26     cout << "s1: " << s1 << endl;
27     cout << "s2: " << s2 << endl;
28 }
29 
30 int main() {
31     cout << "测试1: 使用标准输入流对象cin输入字符串" << endl;
32     test1();
33     cout << endl;
34 
35     cin.ignore(numeric_limits<streamsize>::max(), '\n');
36 
37     cout << "测试2: 使用函数getline()输入字符串" << endl;
38     test2();
39     cout << endl;
40 
41     cout << "测试3: 使用函数getline()输入字符串, 指定字符串分隔符" << endl;
42     test3();
43 }
task4_1.cpp

 

运行测试截图:

 

问题:

1.去掉line35后运行结果截图为

line35在这里的用途是清除输入缓存区中的剩余数据,确保下一次输入操作不会受到之前输入的影响(删除后会有空行产生)

 

(2)

源码:

 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         vector<string> v1;
17 
18         for(int i = 0; i < n; ++i) {
19             string s;
20             cin >> s;
21             v1.push_back(s);
22         }
23 
24         cout << "output v1: " << endl;
25         output(v1); 
26         cout << endl;
27     }
28 }
29 
30 int main() {
31     cout << "测试: 使用cin多组输入字符串" << endl;
32     test();
33 }
task4_2.cpp

 

运行测试截图:

 

(3)

源码:

 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 
31 int main() {
32     cout << "测试: 使用函数getline()多组输入字符串" << endl;
33     test();
34 }
task4_3.cpp

 

运行测试截图: 

 

问题:

1.去掉line16后运行结果截图为

 line16在这里的用途是清除输入缓存区中的剩余数据,确保下一次输入操作不会受到之前输入的影响(删除后会有空字行产生)

 

 

任务5

源码:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 template<typename T>
 5 
 6 class GameResourceManager {
 7 public:
 8     GameResourceManager(T resource0): resource{resource0} {}
 9     ~GameResourceManager() {}
10     T get() const {return resource;}
11     void update(T resource0){
12         if(resource0 > 0)
13             resource += resource0;
14         else
15             resource = max(resource + resource0, static_cast <T>(0));
16     }
17     
18 private:
19     T resource;
20 };
grm.hpp
 1 #include "grm.hpp"
 2 #include <iostream>
 3 
 4 using std::cout;
 5 using std::endl;
 6 
 7 void test1() {
 8     GameResourceManager<float> HP_manager(99.99);
 9     cout << "当前生命值: " << HP_manager.get() << endl;
10     HP_manager.update(9.99);
11     cout << "增加9.99生命值后, 当前生命值: " << HP_manager.get() << endl;
12     HP_manager.update(-999.99);
13     cout <<"减少999.99生命值后, 当前生命值: " << HP_manager.get() << endl;
14 }
15 
16 void test2() {
17     GameResourceManager<int> Gold_manager(100);
18     cout << "当前金币数量: " << Gold_manager.get() << endl;
19     Gold_manager.update(50);
20     cout << "增加50个金币后, 当前金币数量: " << Gold_manager.get() << endl;
21     Gold_manager.update(-99);
22     cout <<"减少99个金币后, 当前金币数量: " << Gold_manager.get() << endl;
23 }
24 
25 
26 int main() {
27     cout << "测试1: 用float类型对类模板GameResourceManager实例化" << endl;
28     test1();
29     cout << endl;
30 
31     cout << "测试2: 用int类型对类模板GameResourceManager实例化" << endl;
32     test2();
33 }
task5.cpp

 

运行测试截图:

 

注:

将更新后的值与0比较时需要将0强制转换为模板类

 

 

任务6

源码:

 1 #pragma once
 2 
 3 #include <string>
 4 #include <iostream>
 5 #include <iomanip>
 6 
 7 using namespace std;
 8 
 9 class Info {
10 private:
11     string nickname;
12     string contact;
13     string city;
14     int n;
15 
16 public:
17     Info(string nickname0, string contact0, string city0, int n0)
18         : nickname{nickname0}, contact{contact0}, city{city0}, n{n0} {}
19 
20     void display() const {
21         cout << setw(10) << "昵称:" << nickname << endl
22             << setw(10) << "联系方式:" << contact << endl
23             << setw(10) << "所在城市:" << city << endl 
24             << setw(10) << "预定参加人数: " << n << endl;
25     }
26 
27     int get_n() const {
28         return n;
29     }
30 };
Info.hpp
 1 #include "info.hpp"
 2 #include <iostream>
 3 #include <vector>
 4 #include <string> 
 5 #include <iomanip>
 6 
 7 const int capacity = 100;
 8 
 9 int main() {
10     vector<Info> audience_lst;
11     int current_capacity = 0;
12 
13     string nickname, contact, city;
14     int n;
15 
16     cout << "录入用户预约信息:" << endl << endl; 
17     cout << left << setw(15) << "昵称" 
18         << setw(30) << "联系方式(邮箱/手机号)" 
19         << setw(15) << "所在城市"  
20         << setw(15) << "预定参加人数 " << endl;
21             
22     while (true) {
23         if (!(cin >> nickname)) break; //多组输入,按下Ctrl+Z时结束 
24         cin >> contact;
25         cin >> city;
26         cin >> n;
27 
28         if (current_capacity + n > capacity) {
29             cout << "对不起,只剩" << capacity - current_capacity << "个位置." << endl;
30             cout << "1.输入u,更新预定信息" << endl << "2.输入q,退出预定" << endl << "你的选择:";
31             char choice;
32             cin >> choice; 
33 
34             if (choice == 'q') {
35                 break;
36             } 
37             else if (choice == 'u') {
38                 cout << "请重新输入预定信息:" << endl;
39                 cin >> nickname >> contact >> city >> n;
40             }
41             else {
42                 cout << "输入无效,请重新输入";
43                 continue;
44             }
45         }
46 
47         Info audience(nickname, contact, city, n);
48         audience_lst.push_back(audience);
49         current_capacity += n;
50         
51         if (current_capacity == capacity) 
52             break;
53     }
54 
55     cout << endl;
56     cout << "截至目前一共有" << current_capacity << "位听众预约。预约听众信息如下:" << endl;
57     for (const auto& info: audience_lst) {
58         info.display();
59         cout << endl;
60     }
61 
62     return 0;
63 }
task6.cpp

 

运行测试截图:

 

 

setw()用于控制输出格式最小长度(iomanip头文件),left左对齐

 

任务7

源码:

 1 //date.h
 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;    //该日期是从公元元年1月1日开始的第几天
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     //计算两个日期之间差多少天
21     int distance(const Date& date) const {
22         return totalDays - date.totalDays;
23     }
24 };
25 #endif //__DATE_H__
date.h
 1 //date.cpp
 2 #include "date.h"
 3 #include <iostream>
 4 #include <cstdlib>
 5 using namespace std;
 6 namespace {    //namespace使下面的定义只在当前文件中有效
 7     //存储平年中的某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项
 8     const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
 9 }
10 Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
11     if (day <= 0 || day > getMaxDay()) {
12         cout << "Invalid date: ";
13         show();
14         cout << endl;
15         exit(1);
16     }
17     int years = year - 1;
18     totalDays = years * 365 + years / 4 - years / 100 + years / 400
19                 + DAYS_BEFORE_MONTH[month - 1] + day;
20     if (isLeapYear() && month > 2) totalDays++;
21 }
22 int Date::getMaxDay() const {
23     if (isLeapYear() && month == 2)
24         return 29;
25     else
26         return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
27 }
28 void Date::show() const {
29     cout << getYear() << "-" << getMonth() << "-" << getDay();
30 }
View Code
 1 //accumulator.h
 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     //构造函数,date为开始累加的日期,value为初始值
12     Accumulator(const Date &date, double value)
13             : lastDate(date), value(value), sum(0) { }
14     //获得到日期date的累加结果
15     double getSum(const Date &date) const {
16         return sum + value * date.distance(lastDate);
17     }
18     //在date将数值变更为value
19     void change(const Date &date, double value) {
20         sum = getSum(date);
21         lastDate = date; this->value = value;
22     }
23     //初始化,将日期变为date,数值变为value,累加器清零
24     void reset(const Date &date, double value) {
25         lastDate = date; this->value = value; sum = 0;
26     }
27 };
28 #endif //__ACCUMULATOR_H__
accumulator.h
 1 //account.h
 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     //供派生类调用的构造函数,id为账户
14     Account(const Date &date, const std::string &id);
15     //记录一笔帐,date为日期,amount为金额,desc为说明
16     void record(const Date &date, double amount, const std::string &desc);
17     //报告错误信息
18     void error(const std::string &msg) const;
19 public:
20     const std::string &getId() const { return id; }
21     double getBalance() const { return balance; }
22     static double getTotal() { return total; }
23     //显示账户信息
24     void show() const;
25 };
26 class SavingsAccount : public Account { //储蓄账户类
27 private:
28     Accumulator acc;    //辅助计算利息的累加器
29     double rate;        //存款的年利率
30 public:
31     //构造函数
32     SavingsAccount(const Date &date, const std::string &id, double rate);
33     double getRate() const { return rate; }
34     //存入现金
35     void deposit(const Date &date, double amount, const std::string &desc);
36     //取出现金
37     void withdraw(const Date &date, double amount, const std::string &desc);
38     void settle(const Date &date);    //结算利息,每年1月1日调用一次该函数
39 };
40 class CreditAccount : public Account { //信用账户类
41 private:
42     Accumulator acc;    //辅助计算利息的累加器
43     double credit;        //信用额度
44     double rate;        //欠款的日利率
45     double fee;            //信用卡年费
46     double getDebt() const {    //获得欠款额
47         double balance = getBalance();
48         return (balance < 0 ? balance : 0);
49     }
50 public:
51     //构造函数
52     CreditAccount(const Date &date, const std::string &id, double credit, double rate, double fee);
53     double getCredit() const { return credit; }
54     double getRate() const { return rate; }
55     double getFee() const { return fee; }
56     double getAvailableCredit() const {    //获得可用信用
57         if (getBalance() < 0)
58             return credit + getBalance();
59         else
60             return credit;
61     }
62     //存入现金
63     void deposit(const Date &date, double amount, const std::string &desc);
64     //取出现金
65     void withdraw(const Date &date, double amount, const std::string &desc);
66     void settle(const Date &date);    //结算利息和年费,每月1日调用一次该函数
67     void show() const;
68 };
69 #endif //__ACCOUNT_H__
account.h
 1 //account.cpp
 2 #include "account.h"
 3 #include <cmath>
 4 #include <iostream>
 5 using namespace std;
 6 double Account::total = 0;
 7 //Account类的实现
 8 Account::Account(const Date &date, const string &id)
 9         : id(id), balance(0) {
10     date.show(); cout << "\t#" << id << " created" << endl;
11 }
12 void Account::record(const Date &date, double amount, const string &desc) {
13     amount = floor(amount * 100 + 0.5) / 100;    //保留小数点后两位
14     balance += amount; total += amount;
15     date.show();
16     cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
17 }
18 void Account::show() const { cout << id << "\tBalance: " << balance; }
19 void Account::error(const string &msg) const {
20     cout << "Error(#" << id << "): " << msg << endl;
21 }
22 //SavingsAccount类相关成员函数的实现
23 SavingsAccount::SavingsAccount(const Date &date, const string &id, double rate)
24         : Account(date, id), rate(rate), acc(date, 0) { }
25 void SavingsAccount::deposit(const Date &date, double amount, const string &desc) {
26     record(date, amount, desc);
27     acc.change(date, getBalance());
28 }
29 void SavingsAccount::withdraw(const Date &date, double amount, const string &desc) {
30     if (amount > getBalance()) {
31         error("not enough money");
32     } else {
33         record(date, -amount, desc);
34         acc.change(date, getBalance());
35     }
36 }
37 void SavingsAccount::settle(const Date &date) {
38     double interest = acc.getSum(date) * rate    //计算年息
39                       / date.distance(Date(date.getYear() - 1, 1, 1));
40     if (interest != 0) record(date, interest, "interest");
41     acc.reset(date, getBalance());
42 }
43 //CreditAccount类相关成员函数的实现
44 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee)
45         : Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) { }
46 void CreditAccount::deposit(const Date &date, double amount, const string &desc) {
47     record(date, amount, desc);
48     acc.change(date, getDebt());
49 }
50 void CreditAccount::withdraw(const Date &date, double amount, const string &desc) {
51     if (amount - getBalance() > credit) {
52         error("not enough credit");
53     } else {
54         record(date, -amount, desc);
55         acc.change(date, getDebt());
56     }
57 }
58 void CreditAccount::settle(const Date &date) {
59     double interest = acc.getSum(date) * rate;
60     if (interest != 0) record(date, interest, "interest");
61     if (date.getMonth() == 1)
62         record(date, -fee, "annual fee");
63     acc.reset(date, getDebt());
64 }
65 void CreditAccount::show() const {
66     Account::show();
67     cout << "\tAvailable credit:" << getAvailableCredit();
68 }
account.cpp
 1 //7_10.cpp
 2 #include "account.h"
 3 #include <iostream>
 4 using namespace std;
 5 int main() {
 6     Date date(2008, 11, 1);    //起始日期
 7     //建立几个账户
 8     SavingsAccount sa1(date, "S3755217", 0.015);
 9     SavingsAccount sa2(date, "02342342", 0.015);
10     CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
11     //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     //12月份的几笔账目
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 }
7_10.cpp

 

运行测试截图:

 

问题:

1.增加了储蓄账户类的派生类信用账户类(公有继承),完善了银行储蓄账户的种类,更加符合生活实际

2.不同派生类的函数相互独立,只有知道对象的具体类型后才能调用

 

posted @ 2024-11-18 18:21  吴婧希  阅读(13)  评论(0)    收藏  举报