实验四 类的组合,继承,模板类,标准库

一、实验目的

 知道什么是类模板,会正确定义和使用简单的类模板

会使用C++正确定义,使用派生类

加深对类的组合机制(has-a),类的继承机制(is-a)的领悟和理解

练习标准库string,vector的用法,能基于问题场景灵活使用

针对具体场景,练习运用面向对象思维进行设计,组合使用标准库和自定义类,编程解决实际问题

二、实验准备

 类模板,

组合类

派生类

 

三、实验内容

 

2. 实验任务2

代码:

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 
 25 private:
 26     void compute();   
 27 
 28 private:
 29     string course_name;     
 30     int n;                  
 31     vector<int> counts = vector<int>(5, 0);      
 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 } 

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 
20 int main() {
21     test();
22 }

 

 

 

运行截图:

 

 

 

问题回答:

 问题一:成绩存储在vector<int>里。

sort通过this->begin(), this->end(),和this->begin(), this->end(), std::greater<int>()使用vector迭代器来访问成绩,

min 通过std::min_element(this->begin(), this->end());访问,

max 通过std::max_element(this->begin(), this->end());来访问,

average通过std::accumulate(this->begin(), this->end(), 0) * 1.0 / n;来访问,

output通过for(auto ptr = this->begin(); ptr != this->end(); ++ptr)来访问成绩,

input 使用this ->push_back(grade)将用户输入的成绩存入gradecalc对象中。

问题二:

 第68行代码返回成绩的平均值,去掉1.0后,结果被截断,只有整数部分了,故而乘以1.0的目的

在于计算过程是浮点数除法,并且结果也能够得到小数部分。

问题三:

1,input的输入还需进行有效性检查,负数和超过100的数应设置提醒。

2,成绩的类型如果是小数例如89.99,当前的就不支持了,可以考虑用实验一的方式模板化设计支持任何数字类型输入处理

3,在实际生活中,不仅仅需要这些功能,可以考虑增加其它功能,方差,中位数等。

3. 实验任务3

代码:

 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 {
 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);      
 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 } 

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 
20 int main() {
21     test();
22 }

 

 

运行截图:

 

 

 

 问题回答:

问题一:gradecalc定义中,成绩存储在 vector<int> grades;当中,

sort 通过std::sort(grades.begin(), grades.end());和 std::sort(grades.begin(), grades.end(), std::greater<int>());访问

min通过std::min_element(grades.begin(), grades.end());访问

max通过std::max_element(grades.begin(), grades.end());访问

average通过std::accumulate(grades.begin(), grades.end(), 0) * 1.0 / n;访问

output通过for(int grade: grades)循环来访问

细微差别在于实验二用的是一个->this指针和,这里用的是grades

问题二:

 实验二的设计用一个继承std::vector<int>来实现数据存储,而实验三用成绩grades作为私有的成员在类的内部进行管理

实现了封装,代码可读性提高,而且也保证 了对数据的管理,在外部就不能直接访问修改内部的状态,

封装就是只需关注如何使用类,而不必了解内部实现的机制。是面向对象的一个特点之一。

 

4. 实验任务4

代码:

 task1:

 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;
11     cout<<"s2: "<<s2<<endl;    
12 }
13 
14 void test2(){
15     string s1,s2;
16     getline(cin,s1);
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     
38     cout<<"测试2: 使用函数getline()输入字符串"<<endl;
39     test2();
40     cout<<endl;
41     
42     cout<<"测试3:使用函数getline()输入字符串,指定字符串分隔符"<<endl;
43     test3();
44     
45      
46 }

 task2:

 1 #include<iostream>
 2 #include<string>
 3 #include<limits>
 4 #include<vector>
 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 
14 
15 void test(){
16     int n;
17     
18     while(cout<<"Enter n: ",cin>>n){
19         vector<string> v1;
20         for(int i=0;i<n;++i){
21             string s;
22             cin>>s;
23             v1.push_back(s);
24         }
25         cout<<"output v1: "<<endl;
26         output(v1);
27         cout<<endl;
28     } 
29     
30 }
31 
32 
33 
34 int main(){
35     cout<<"测试: 使用cin多组输入字符串"<<endl;
36     
37     test();
38     
39      
40 }

task3:

 1 #include<iostream>
 2 #include<string>
 3 #include<limits>
 4 #include<vector>
 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 
14 
15 void test(){
16     int n;
17     
18     while(cout<<"Enter n: ",cin>>n){
19         cin.ignore(numeric_limits<streamsize>::max(),'\n');//变化处 
20         vector<string> v2;
21         for(int i=0;i<n;++i){
22             string s;
23             getline(cin,s);//变化处 
24             
25             
26             v2.push_back(s);
27         }
28         cout<<"output v2: "<<endl;
29         output(v2);
30         cout<<endl;
31     } 
32     
33 }
34 
35 
36 
37 int main(){
38     cout<<"测试: 使用cin多组输入字符串"<<endl;
39     
40     test();
41     
42      
43 }

 

 

运行截图:

 task1:

注释掉cin.ignore(numeric_limits<streamsize>::max(),'\n' );之前的结果

 注释掉cin.ignore(numeric_limits<streamsize>::max(),'\n' );之后的结果

 

 task2:

task3:

去掉cin.ignore(numeric_limits<streamsize>::max(),'\n');之前

去掉cin.ignore(numeric_limits<streamsize>::max(),'\n');之后:

 

 问题回答:

 问题一:cin.ignore(numeric_limits<streamsize>::max(),'\n' );

用于清除输入缓冲区中的剩余字符,直到遇到换行符或者达到指定的最大字符数在代码中

在这个代码当中的使用是为了确保在调用 getline读取新输入之前,清除输入缓冲区中的换行符,从而避免影响后续输入的结果

问题二:

作用是清除输入缓冲区中的换行符,以确保后续通过 getline() 函数读取的字符串能够正确获取用户的输入,而不是误读取到一个空字符串。

 

 

5. 实验任务5

代码:

 grm.hpp

 1 #ifndef GRM_HPP
 2 #define GRM_HPP
 3 
 4 template<typename T>
 5 class GameResourceManager {
 6 public:
 7  
 8     GameResourceManager(T num1);
 9 
10   
11     T get() const;
12 
13   
14     void update(T num2);
15 
16 private:
17     T resource; 
18 };
19 
20 
21 template<typename T>
22 GameResourceManager<T>::GameResourceManager(T num1) : resource(num1) {}
23 
24 template<typename T>
25 T GameResourceManager<T>::get() const {
26     return resource;
27 }
28 
29 template<typename T>
30 void GameResourceManager<T>::update(T num2) {
31     resource += num2;
32     if (resource < 0) {
33         resource = 0; 
34     }
35 }
36 
37 #endif

grm_test.cpp

 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 }

 

 

运行截图:

 

 

 

 

 

 

 

6. 实验任务6

代码:

 info.hpp

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <string> 
 5 
 6 using std::cin;
 7 using std::cout;
 8 using std::endl;
 9 using std::string;
10 
11 class Info {
12 private:
13     string nickname;
14     string contact;
15     string city;
16     int n;
17 
18 public:
19     Info(const string name, const string phone_or_name, const string place, int num) : nickname{name}, contact{phone_or_name}, city{place}, n{num} {}
20     void display() const ;
21     int getnum() const; 
22 };
23 
24 void Info::display() const{
25     cout << "_______________________________________" << endl; 
26     cout << "昵称:\t" << nickname << endl;
27     cout << "联系方式:\t" << contact << endl;
28     cout << "所在城市:\t" << city << endl;
29     cout << "预定人数:\t" << n << endl;    
30 }
31 
32 int Info::getnum() const { 
33     return n;
34 }

task6.cpp

 1 #include <iostream>
 2 #include <vector> 
 3 #include <limits>
 4 #include "info.hpp"
 5 
 6 using namespace std;
 7 
 8 const int capacity = 100;
 9 
10 int main() {
11     
12     cout<<"欢迎来到预约登记系统:"<<endl;
13     
14     vector<Info> audience_lst;
15     int cur_num = 0; 
16 
17     while (true) {
18         string nickname, contact, city;
19         int n;
20 
21         cout << "请输入昵称:";
22          if (!getline(cin, nickname)) {
23             break; 
24         }
25       
26 
27         cout << "请输入联系方式 (邮箱或手机号): ";
28         getline(cin, contact);
29 
30         cout << "请输入所在城市: ";
31         getline(cin, city);
32 
33         cout << "请输入预定参加人数: ";
34         cin >> n;
35         cin.ignore(numeric_limits<streamsize>::max(), '\n'); // 清除输入缓冲区
36 
37         // 超过容量检查
38         if (cur_num + n > capacity) {
39             cout << "预定人数超过剩余容量!目前只剩下" << capacity - cur_num << "个位置" << endl;
40             cout << "1: 输入q退出预定" << endl;
41             cout << "2: 输入u更新预定信息" << endl;
42 
43             char option;
44             cout << "你的选择:";
45             cin >> option;
46             cin.ignore(numeric_limits<streamsize>::max(), '\n'); // 清除输入缓冲区
47 
48             if (option == 'q') {
49                 break;
50             } else if (option == 'u') {
51                 continue;
52             } else {
53                 cout << "无效选项,重新输入。" << endl;
54                 continue;
55             }
56         }
57 
58         audience_lst.emplace_back(nickname, contact, city, n);
59         cur_num += n;
60 
61         // 输出当前预约人数
62         cout << "当前已预定人数: " << cur_num << endl;
63 
64         // 如果达到最大容量,结束输入
65         if (cur_num >= capacity) {
66             cout << "已达到最大预定人数,停止预约。" << endl;
67             break;
68         }
69     }
70 
71     // 打印所有用户信息
72     cout << "截止目前,一共有" << cur_num << "位用户预约。预约听众信息如下:" << endl;
73 
74     for (const auto &audience : audience_lst) {
75         audience.display();
76     }
77 
78     return 0;
79 }

 

 

运行截图:

 测试一:

测试二:

 

 

 

 

 

 

7. 实验任务7

代码:

 date.h

 1 #pragma once
 2 
 3 #ifndef  _DATE_H__
 4 #define _DATE_H__
 5 
 6 class Date{
 7     private:
 8         
 9         int year;
10         
11         int month;
12         
13         int day;
14         
15         int totalDays;
16         
17         
18     public:
19         Date(int year, int month, int day);
20         
21         int getYear()const {return year;}
22         
23         int getMonth()const {return month;}
24         
25         int getDay() const{return day ;}
26         
27         int getMaxDay()  const;
28         
29         bool isLeapYear () const{
30         return year%4 == 0 &&year %100!=0 ||year %400 ==0;
31         }
32         void show()const;
33         
34         int distance(const Date& date )const{
35         return totalDays - date.totalDays;}
36         
37 };
38 
39 #endif//_DATE_H__

date.cpp

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

accumulator.h

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

account.h

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

 

 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  }

task.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 }

 

运行截图:

 

 

posted @ 2024-11-23 21:22  安东尼23  阅读(9)  评论(0编辑  收藏  举报