實驗四 類的組合,繼承,模板類,標準庫

安东尼23發表於2024-11-23

一、實驗目的

知道什麼是類别範本,會正確定義和使用簡單的類别範本

會使用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 }

執行截圖:

相關文章