類的組合、繼承、模板類、標準庫

nightlight發表於2024-11-24

實驗任務一:

類的組合、繼承、模板類、標準庫
 1  #include <iostream>
 2   
 3   using std::cout;
 4   using std::endl;
 5   
 6   // 類A的定義
 7   class A {
 8   public:
 9       A(int x0, int y0);
10      void display() const;
11  
12  private:
13      int x, y;
14  };
15  
16  A::A(int x0, int y0): x{x0}, y{y0} {
17  }
18  
19  void A::display() const {
20      cout << x << ", " << y << endl;
21  }
22 
23 // 類B的定義
24  class B {
25  public:
26      B(double x0, double y0);
27      void display() const;
28  
29  private:
30      double x, y;
31  };
32  
33  B::B(double x0, double y0): x{x0}, y{y0} {
34  }
35  
36  void B::display() const {
37      cout << x << ", " << y << endl;
38  }
39  
40  void test() {
41      cout << "測試類A: " << endl;
42      A a(3, 4);
43      a.display();
44  
45      cout << "\n測試類B: " << endl;
46      B b(3.2, 5.6);
47      b.display();
48  }
49  
50  int main() {
51      test();
52  }
task1_1
類的組合、繼承、模板類、標準庫
 1  #include <iostream>
 2   #include <string>
 3   
 4   using std::cout;
 5  using std::endl;
 6   using std::string;
 7   
 8   // 定義類别範本
 9   template<typename T>
10  class X{
11  public:
12      X(T x0, T y0);
13      void display();
14  
15  private:
16      T x, y;
17  };
18  
19  template<typename T>
20  X<T>::X(T x0, T y0): x{x0}, y{y0} {
21  }
22  
23  template<typename T>
24  void X<T>::display() {
25      cout << x << ", " << y << endl;
26  }
27  
28  
29  void test() {
30      cout << "測試1: 類别範本X中的抽象型別T用int例項化" << endl;
31      X<int> x1(3, 4);
32      x1.display();
33     
34      cout << endl;
35  
36      cout << "測試2: 類别範本X中的抽象型別T用double例項化" << endl;
37      X<double> x2(3.2, 5.6);
38      x2.display();
39  
40    cout << endl;
41  
42      cout << "測試3: 類别範本X中的抽象型別T用string例項化" << endl;
43      X<string> x3("hello", "oop");
44      x3.display();
45  }
46  
47  int main() {
48      test();
49  }
task1_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
類的組合、繼承、模板類、標準庫task2.cpp

問題一:

成績儲存在vector<int>類陣列中;sort,min,max,average,output是透過vector<int>中的begin(),end()介面訪問每個成績的;input是透過vector<int>中的push_back()介面實現資料存入物件的

問題二:

功能:分母為人數,用來計算總分數的平均值;去掉*1.0程式碼,結果影響了平均分精度;*1.0是為提高精度的

問題三:

可以考慮使用動態陣列,便於更新已有成績或增減成員。

可以增加成績中位數、標準差等指標。

增加引數設定,使得輸出資訊可以自定義,例如輸出成績分佈、分數段詳情等

實驗任務三:

類的組合、繼承、模板類、標準庫
  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:成績被儲存在類的私有成員grades中,其型別為vector<int>。對於排序、求最值、計算平均值和輸出等操作,都是透過grades.begin()和grades.end()介面來訪問成績的。與之前的程式碼相比,這次實驗新增了vector<int>型別的counts和vector<double>型別的rates物件,而在類的成員方法中,直接透過grades.來呼叫繼承的相關方法。

問題2:物件導向程式設計允許在不改變主要程式碼邏輯和介面的情況下對類的設計介面及內部細節進行修改。這樣可以使程式碼的修改和最佳化更加方便和可控。

實驗任務四:

類的組合、繼承、模板類、標準庫
 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.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         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

類的組合、繼承、模板類、標準庫
 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

問題二:修改後結果

用途:清除輸入流中未被 cin >> n 讀取的換行符,以確保接下來的 getline 函式可以正確讀取使用者輸入的字串,避免由於殘留的換行符導致它立即返回空字串。

實驗任務五:

類的組合、繼承、模板類、標準庫
 1 #include<iostream>
 2 
 3 
 4 using std::cout;
 5 using std::endl;
 6 
 7 template<typename T>
 8 class GameResourceManager{
 9     public:
10         GameResourceManager(T x0);
11         T get();
12         void update(T y0);
13     private:
14         T x;
15 };
16 
17 template<typename T>
18 GameResourceManager<T>::GameResourceManager(T x0):x{x0} {
19 }
20 
21 template<typename T>
22 T GameResourceManager<T>::get() {
23     return x;
24 }
25 
26 template<typename T>
27 void GameResourceManager<T>::update(T y0) {
28     x+=y0;
29     if(x<0)
30         x=0;
31 }
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

實驗任務六

類的組合、繼承、模板類、標準庫
 1 #include<iostream>
 2 #include<string>
 3 #include <iomanip>
 4 
 5 using std::cout;
 6 using std::endl;
 7 using std::string;
 8 using std::setw;
 9 
10 class Info{
11     public:
12         Info(string nickname0,string contact0,string city0,int n0);
13         void display();
14     private:
15         string nickname;
16         string contact;
17         string city;
18         int n;
19 };
20 
21 Info::Info(string nickname0,string contact0,string city0,int n0):nickname(nickname0),contact(contact0),city(city0),n(n0) {
22 }
23 
24 void Info::display()
25 {
26 
27     cout<<"-------------------------------\n";
28     cout<<setw(10)<<"暱稱"<<nickname<<endl;
29     cout<<setw(10)<<"聯絡方式"<<contact<<endl;
30     cout<<setw(10)<<"所在城市"<<city<<endl;
31     cout<<setw(10)<<"預定人數"<<n<<endl;
32 }
info.hpp
類的組合、繼承、模板類、標準庫
 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 #include <iomanip>
 5 #include"info.hpp"
 6 
 7 using namespace std;
 8 using std::setw;
 9 
10 int main()
11 {
12     const int capacity=100;
13     vector<Info> audience_lst;
14     char choice;
15     string nickname,contact,city;
16     int n;
17     cout<<"錄入使用者預約資訊:\n"<<endl;
18     cout<<"暱稱"<<setw(30)<<"聯絡方式(郵箱/手機號)"<<setw(20)<<"所在城市"<<setw(20)<<"預定參加人數"<<endl;
19     int i=0,sum=0;
20     while((cin>>nickname>>contact>>city>>n))
21     {
22         //cin>>nickname>>contact>>city>>n;
23         audience_lst.push_back(Info(nickname,contact,city,n));
24         sum+=n;
25         i++;
26         if(sum>capacity)
27        {
28            sum-=n;
29         cout<<"對不起,只剩"<<capacity-sum<<"個位置。\n";
30         cout<<"1.輸入u,更新(update)預定資訊\n";
31         cout<<"2.輸入q,退出預定\n";
32         cout<<"你的選擇:";
33         cin>>choice;
34         if(choice=='u')
35         {
36             cout<<"請重新輸入預定資訊:\n";
37             i--;
38             continue;
39         }
40         else
41         {
42             break;
43         }
44        }
45 
46     }
47 
48     cout<<"截至目前,一共有"<<sum<<"位聽眾預約。預約聽眾資訊如下:\n";
49     for(int j=0;j<i;j++)
50     {
51         audience_lst[j].display();
52     }
53 }
task6.cp

實驗任務7:

類的組合、繼承、模板類、標準庫
 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 }
task7.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 }
account.cpp
類的組合、繼承、模板類、標準庫
 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
account.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
accumulator.h
類的組合、繼承、模板類、標準庫
 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 
20 int Date::getMaxDay() const {
21     if(isLeapYear()&&month==2)
22         return 29;
23     else
24         return DAYS_BEFORE_MONTH[month]-DAYS_BEFORE_MONTH[month-1];
25 }
26 
27 void Date::show()  const {
28     cout<<getYear()<<"-"<<getMonth()<<"-"<<getDay();
29 }
date.cpp
類的組合、繼承、模板類、標準庫
 1 #ifndef __DATE_H__
 2 #define __DATE_H__
 3 class Date{
 4     private:
 5         int year;
 6         int month;
 7         int day;
 8         int totalDays;
 9     public:
10         Date(int year,int month,int day);
11         int getYear() const {return year;}
12         int getMonth() const {return month;}
13         int getDay() const {return day;}
14         int getMaxDay() const;
15         bool isLeapYear() const {
16             return year%4==0 && year%100 !=0 ||year%400==0;
17         }
18         void show() const;
19 
20         int distance(const Date& date) const {
21             return totalDays-date.totalDays;
22         }
23 };
24 #endif //__DATE_H__
date.h

運用了類的派生的思想,使得派生類處理每一筆具體賬目時可以呼叫record函式來改變餘額並輸出賬目資訊,提高了程式碼複用性。

透過採用繼承方式,降低了程式碼的重複性,從而實現功能的擴充套件,使得程式在後續的修改和維護中更加方便。

實驗總結:

在本次實驗中,我深入學習了C++中的類别範本和派生類的定義與使用,掌握瞭如何透過類的組合機制(has-a)和繼承機制(is-a)來設計靈活的類結構。透過實踐標準庫中的stringvector,我能夠根據具體問題場景靈活運用這些工具。此外,我運用物件導向的思維進行設計,結合標準庫和自定義類,成功解決了實際問題。這次實驗不僅加深了我對C++物件導向程式設計的理解,也提升了我的程式設計能力和問題解決能力。

相關文章