c++程式設計基礎實驗4

相梓文發表於2024-11-24

任務2:


原始碼:

Gradecalc.hpp:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <iomanip>

using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;

class GradeCalc: public vector<int> {
public:
    GradeCalc(const string &cname, int size);      
    void input();                             // 錄入成績
    void output() const;                      // 輸出成績
    void sort(bool ascending = false);        // 排序 (預設降序)
    int min() const;                          // 返回最低分
    int max() const;                          // 返回最高分
    float average() const;                    // 返回平均分
    void info();                              // 輸出課程成績資訊 

private:
    void compute();     // 成績統計

private:
    string course_name;     // 課程名
    int n;                  // 課程人數
    vector<int> counts = vector<int>(5, 0);      // 儲存各分數段人數([0, 60), [60, 70), [70, 80), [80, 90), [90, 100]
    vector<double> rates = vector<double>(5, 0); // 儲存各分數段比例 
};

GradeCalc::GradeCalc(const string &cname, int size): course_name{cname}, n{size} {}   

void GradeCalc::input() {
    int grade;

    for(int i = 0; i < n; ++i) {
        cin >> grade;
        this->push_back(grade);
    } 
}  

void GradeCalc::output() const {
    for(auto ptr = this->begin(); ptr != this->end(); ++ptr)
        cout << *ptr << " ";
    cout << endl;
} 

void GradeCalc::sort(bool ascending) {
    if(ascending)
        std::sort(this->begin(), this->end());
    else
        std::sort(this->begin(), this->end(), std::greater<int>());//std::greater<int>()可以讓陣列進行降序排列
}  

int GradeCalc::min() const {
    return *std::min_element(this->begin(), this->end());
}  //加上*表示解引用,返回的是一個迭代器,要加上解引用才能返回迭代器的值

int GradeCalc::max() const {
    return *std::max_element(this->begin(), this->end());
}    

float GradeCalc::average() const {
    return std::accumulate(this->begin(), this->end(), 0) * 1.0 / n;
}   

void GradeCalc::compute() {
    for(int grade: *this) {
        if(grade < 60)
            counts.at(0)++;
        else if(grade >= 60 && grade < 70)
            counts.at(1)++;
        else if(grade >= 70 && grade < 80)
            counts.at(2)++;
        else if(grade >= 80 && grade < 90)
            counts.at(3)++;
        else if(grade >= 90)
            counts.at(4)++;
    }

    for(int i = 0; i < rates.size(); ++i)
        rates.at(i) = counts.at(i) * 1.0 / n;
}

void GradeCalc::info()  {
    cout << "課程名稱:\t" << course_name << endl;
    cout << "排序後成績: \t";
    sort();  output();
    cout << "最高分:\t" << max() << endl;
    cout << "最低分:\t" << min() << endl;
    cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl;
    
    compute();  // 統計各分數段人數、比例

    vector<string> tmp{"[0, 60)  ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"};
    for(int i = tmp.size()-1; i >= 0; --i)
        cout << tmp[i] << "\t: " << counts[i] << "人\t" 
             << std::fixed << std::setprecision(2) << rates[i]*100 << "%" << endl; 
} 

demo2.cpp:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <iomanip>

using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;

class GradeCalc: public vector<int> {
public:
    GradeCalc(const string &cname, int size);      
    void input();                             // 錄入成績
    void output() const;                      // 輸出成績
    void sort(bool ascending = false);        // 排序 (預設降序)
    int min() const;                          // 返回最低分
    int max() const;                          // 返回最高分
    float average() const;                    // 返回平均分
    void info();                              // 輸出課程成績資訊 

private:
    void compute();     // 成績統計

private:
    string course_name;     // 課程名
    int n;                  // 課程人數
    vector<int> counts = vector<int>(5, 0);      // 儲存各分數段人數([0, 60), [60, 70), [70, 80), [80, 90), [90, 100]
    vector<double> rates = vector<double>(5, 0); // 儲存各分數段比例 
};

GradeCalc::GradeCalc(const string &cname, int size): course_name{cname}, n{size} {}   

void GradeCalc::input() {
    int grade;

    for(int i = 0; i < n; ++i) {
        cin >> grade;
        this->push_back(grade);
    } 
}  

void GradeCalc::output() const {
    for(auto ptr = this->begin(); ptr != this->end(); ++ptr)
        cout << *ptr << " ";
    cout << endl;
} 

void GradeCalc::sort(bool ascending) {
    if(ascending)
        std::sort(this->begin(), this->end());
    else
        std::sort(this->begin(), this->end(), std::greater<int>());//std::greater<int>()可以讓陣列進行降序排列
}  

int GradeCalc::min() const {
    return *std::min_element(this->begin(), this->end());
}  //加上*表示解引用,返回的是一個迭代器,要加上解引用才能返回迭代器的值

int GradeCalc::max() const {
    return *std::max_element(this->begin(), this->end());
}    

float GradeCalc::average() const {
    return std::accumulate(this->begin(), this->end(), 0) * 1.0 / n;
}   

void GradeCalc::compute() {
    for(int grade: *this) {
        if(grade < 60)
            counts.at(0)++;
        else if(grade >= 60 && grade < 70)
            counts.at(1)++;
        else if(grade >= 70 && grade < 80)
            counts.at(2)++;
        else if(grade >= 80 && grade < 90)
            counts.at(3)++;
        else if(grade >= 90)
            counts.at(4)++;
    }

    for(int i = 0; i < rates.size(); ++i)
        rates.at(i) = counts.at(i) * 1.0 / n;
}

void GradeCalc::info()  {
    cout << "課程名稱:\t" << course_name << endl;
    cout << "排序後成績: \t";
    sort();  output();
    cout << "最高分:\t" << max() << endl;
    cout << "最低分:\t" << min() << endl;
    cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl;
    
    compute();  // 統計各分數段人數、比例

    vector<string> tmp{"[0, 60)  ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"};
    for(int i = tmp.size()-1; i >= 0; --i)
        cout << tmp[i] << "\t: " << counts[i] << "人\t" 
             << std::fixed << std::setprecision(2) << rates[i]*100 << "%" << endl; 
} 

執行結果截圖:

問題1:

該派生類為vector<int>容器類的派生類,因此錄入的成績都儲存在派生類的private資料中,雖然在程式碼中沒有體現,但是在c++的標準庫中含有vector容器類的宣告和定義。

上述的函式都是透過vector容器類的public函式訪問成績的資料的,input()函式是透過vector容器類中的push—back()函式介面來輸入資料並儲存在派生類中的,push-back()集團口可以實現在vector<int>動態陣列後面增加錄入元素。

問題2:
分母的作用是計算各個分數區間的人數佔總人數的小數比值,透過乘以1.0,可以將分子上的數值轉換為double型,在計算後可以實現產生小數,方便後續計算百分比時的保留兩位小數輸出。如果不乘以1.0,編譯器就會呼叫整型數的整除,這樣幾個百分比都會變成0。

問題3:
該專案雖然可以宏觀計算成績的資料,但是對於每一個學生的資料統計不完善,可以在後續的派生類中加入學號,姓名,排名等private資料成員,使每一個學生的成績更加直觀。可以在public介面加入查詢功能,透過學號或者姓名來查詢成績。或者透過成績來輸出該成績的學生的個人資訊,更符合實際的應用場景。

任務3:

原始碼:

Gradecalc.hpp:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <iomanip>

using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;

class GradeCalc {
public:
    GradeCalc(const string &cname, int size);      
    void input();                             // 錄入成績
    void output() const;                      // 輸出成績
    void sort(bool ascending = false);        // 排序 (預設降序)
    int min() const;                          // 返回最低分
    int max() const;                          // 返回最高分
    float average() const;                    // 返回平均分
    void info();                              // 輸出課程成績資訊 

private:
    void compute();     // 成績統計

private:
    string course_name;     // 課程名
    int n;                  // 課程人數
    vector<int> grades;     // 課程成績
    vector<int> counts = vector<int>(5, 0);      // 儲存各分數段人數([0, 60), [60, 70), [70, 80), [80, 90), [90, 100]
    vector<double> rates = vector<double>(5, 0); // 儲存各分數段比例 
};

GradeCalc::GradeCalc(const string &cname, int size): course_name{cname}, n{size} {}   

void GradeCalc::input() {
    int grade;

    for(int i = 0; i < n; ++i) {
        cin >> grade;
        grades.push_back(grade);
    } 
}  

void GradeCalc::output() const {
    for(int grade: grades)
        cout << grade << " ";
    cout << endl;
} 

void GradeCalc::sort(bool ascending) {
    if(ascending)
        std::sort(grades.begin(), grades.end());
    else
        std::sort(grades.begin(), grades.end(), std::greater<int>());
        
}  

int GradeCalc::min() const {
    return *std::min_element(grades.begin(), grades.end());
}  

int GradeCalc::max() const {
    return *std::max_element(grades.begin(), grades.end());
}    

float GradeCalc::average() const {
    return std::accumulate(grades.begin(), grades.end(), 0) * 1.0 / n;
}   

void GradeCalc::compute() {
    for(int grade: grades) {
        if(grade < 60)
            counts.at(0)++;
        else if(grade >= 60 && grade < 70)
            counts.at(1)++;
        else if(grade >= 70 && grade < 80)
            counts.at(2)++;
        else if(grade >= 80 && grade < 90)
            counts.at(3)++;
        else if(grade >= 90)
            counts.at(4)++;
    }

    for(int i = 0; i < rates.size(); ++i)
        rates.at(i) = counts.at(i) *1.0 / n;
}

void GradeCalc::info()  {
    cout << "課程名稱:\t" << course_name << endl;
    cout << "排序後成績: \t";
    sort();  output();
    cout << "最高分:\t" << max() << endl;
    cout << "最低分:\t" << min() << endl;
    cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl;
    
    compute();  // 統計各分數段人數、比例

    vector<string> tmp{"[0, 60)  ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"};
    for(int i = tmp.size()-1; i >= 0; --i)
        cout << tmp[i] << "\t: " << counts[i] << "人\t" 
             << std::fixed << std::setprecision(2) << rates[i]*100 << "%" << endl; 
} 

demo3.cpp:

#include "GradeCalc.hpp"
#include <iomanip>

void test() {
    int n;
    cout << "輸入班級人數: ";
    cin >> n;

    GradeCalc c1("OOP", n);

    cout << "錄入成績: " << endl;;
    c1.input();
    cout << "輸出成績: " << endl;
    c1.output();

    cout << string(20, '*') + "課程成績資訊"  + string(20, '*') << endl;
    c1.info();
}

int main() {
    test();
}

執行結果截圖:

問題1:

該段程式碼儲存在vector動態陣列中,上述函式都是透過vector<int>grade動態陣列中的public介面來實現對成績的訪問和處理的。

該段程式碼和任務2的區別主要是,任務2的程式碼更多的使用了this指標對vector容器類的begin(),end()介面去實現資料的數額u輸出和計算,而任務3則直接對vector容器類的介面進行了呼叫,寫法更加地直接。

問題二:

同一個專案在處理問題和架構結構時,可以使用不同的方法,可以運用指標來訪問和處理資料,也可以利用標準庫中的函式和介面來處理,雖然都能實現相同的結果,但是我們在處理資料時如果充分利用標註庫的介面和函式,能夠簡化專案的程式碼的結構複雜度,也能夠提高程式碼的可讀性,更能方便後續的修改和擴充結構。相反,如果自己建立和宣告新的結構時,雖然功能都可以實現,但是在後續的改進和更新中會不可避免得導致結構的改變,還有可能導致資料的洩露,結構的不安全性,因此要充分理解並熟練運用標準庫的內容和介面,如STL容器的各種處理容器資料的函式介面,它們都是安全且穩定的介面;

任務4:

原始碼:

task4-1.cpp:

#include <iostream>
#include <string>
#include <limits>

using namespace std;

void test1() {
    string s1, s2;
    cin >> s1 >> s2;  // cin: 從輸入流讀取字串, 碰到空白符(空格/回車/Tab)即結束
    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
}

void test2() {
    string s1, s2;
    getline(cin, s1);  // getline(): 從輸入流中提取字串,直到遇到換行符
    getline(cin, s2);
    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
}

void test3() {
    string s1, s2;
    getline(cin, s1, ','); //從輸入流中提取字串,直到遇到指定分隔符
    getline(cin, s2);
    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
}

int main() {
    cout << "測試1: 使用標準輸入流物件cin輸入字串" << endl;
    test1();
    cout << endl;

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

    cout << "測試2: 使用函式getline()輸入字串" << endl;
    test2();
    cout << endl;

    cout << "測試3: 使用函式getline()輸入字串, 指定字串分隔符" << endl;
    test3();
}

執行結果截圖:
註釋:將定義間隔符換為了','

問題:

在將該行程式碼去除後,測試2將無法讀取第一個元素,這是因為cin輸入流的緩衝區還儲存了第一次輸入的空格,而緩衝區沒有被及時清除導致了第二次輸入時預設將空白讀取為了s1,因此s1無法被讀取,我們要輸入的s1因為原本的位置被讀取,所以被編譯器賦值到了s2。因此,推測該行程式碼的作用是清除緩衝區的記憶體。

task4-2.cpp:

#include <iostream>
#include <string>
#include <vector>
#include <limits>

using namespace std;

void output(const vector<string> &v) {
    for(auto &s: v)
        cout << s << endl;
}

void test() {
    int n;
    while(cout << "Enter n: ", cin >> n) {
        vector<string> v1;

        for(int i = 0; i < n; ++i) {
            string s;
            cin >> s;
            v1.push_back(s);
        }

        cout << "output v1: " << endl;
        output(v1); 
        cout << endl;
    }
}

int main() {
    cout << "測試: 使用cin多組輸入字串" << endl;
    test();
}

執行結果截圖:

task-3.cpp:

#include <iostream>
#include <string>
#include <vector>
#include <limits>

using namespace std;

void output(const vector<string> &v) {
    for(auto &s: v)
        cout << s << endl;
}

void test() {
    int n;
    while(cout << "Enter n: ", cin >> n) {
        cin.ignore(numeric_limits<streamsize>::max(), '\n');

        vector<string> v2;

        for(int i = 0; i < n; ++i) {
            string s;
            getline(cin, s);
            v2.push_back(s);
        }
        cout << "output v2: " << endl;
        output(v2); 
        cout << endl;
    }
}

int main() {
    cout << "測試: 使用函式getline()多組輸入字串" << endl;
    test();
}

執行結果截圖:

問題:

該段程式碼的作用是清除輸入快取區的快取,避免快取區存取的字串被錯誤讀取。

任務5:

原始碼:
grm.hpp:

#ifndef GRM_HPP
#define GRM_HPP

template <typename T>
class GameResourceManager {
private:
    T resource; // 資源的當前值

public:
    // 建構函式,初始化資源的初始值
    explicit GameResourceManager(T initial_value) : resource(initial_value) {}

    // 獲取當前資源值
    T get() const {
        return resource;
    }

    // 更新資源值
    void update(T delta) {
        resource += delta;
        if (resource < 0) {
            resource = 0; // 防止資源值低於0
        }
    }
};

#endif // GRM_HPP

task5.cpp:

#include "grm.hpp"
#include <iostream>

using std::cout;
using std::endl;

void test1() {
    GameResourceManager<float> HP_manager(99.99);
    cout << "當前生命值: " << HP_manager.get() << endl;
    HP_manager.update(9.99);
    cout << "增加9.99生命值後, 當前生命值: " << HP_manager.get() << endl;
    HP_manager.update(-999.99);
    cout << "減少999.99生命值後, 當前生命值: " << HP_manager.get() << endl;
}

void test2() {
    GameResourceManager<int> Gold_manager(100);
    cout << "當前金幣數量: " << Gold_manager.get() << endl;
    Gold_manager.update(50);
    cout << "增加50個金幣後, 當前金幣數量: " << Gold_manager.get() << endl;
    Gold_manager.update(-99);
    cout << "減少99個金幣後, 當前金幣數量: " << Gold_manager.get() << endl;
}


int main() {
    cout << "測試1: 用float型別對類别範本GameResourceManager例項化" << endl;
    test1();
    cout << endl;

    cout << "測試2: 用int型別對類别範本GameResourceManager例項化" << endl;
    test2();
}

執行結果截圖:

任務6:

原始碼:
info.hpp:

#ifndef INFO_HPP
#define INFO_HPP

#include <string>
#include <iostream>
using std::string;
using std::cout;
using std::endl;

class Info {
private:
    string nickname;   // 暱稱
    string contact;    // 聯絡方式 (email 或手機號)
    string city;       // 所在城市
    int num_people;    // 預定人數

public:
    // 帶引數的建構函式
    Info(const string& nickname, const string& contact, const string& city, int num_people)
        : nickname(nickname), contact(contact), city(city), num_people(num_people) {
    }

    // 顯示資訊
    void display() const {
        cout << "暱稱: " << nickname
            << ", 聯絡方式: " << contact
            << ", 所在城市: " << city
            << ", 預定參加人數: " << num_people << endl;
    }

    // 獲取預定人數
    int get_num_people() const {
        return num_people;
    }

    // 更新預定人數
    void update_num_people(int new_num_people) {
        num_people = new_num_people;
    }
};

#endif // INFO_HPP

task6.cpp:

#include "info.hpp"
#include <vector>
#include <iostream>
using std::vector;
using std::cin;
using std::cout;
using std::endl;

int main() {
    const int capacity = 100;            // livehouse最多容納人數
    int remaining_capacity = capacity;  // 剩餘容量
    vector<Info> audience_lst;          // 存放預約使用者的資訊

    while (remaining_capacity > 0) {
        cout << "請輸入預約資訊 (暱稱、聯絡方式、所在城市、預定人數):" << endl;

        string nickname, contact, city;
        int num_people;

        // 從鍵盤輸入資訊
        cin >> nickname >> contact >> city >> num_people;

        // 檢查是否輸入超出剩餘容量
        if (num_people > remaining_capacity) {
            cout << "剩餘容量不足,最多還可預定: " << remaining_capacity << " 人。" << endl;
            cout << "請輸入 'q' 退出預定,或 'u' 更新預定人數:" << endl;

            char choice;
            cin >> choice;

            if (choice == 'q') {
                cout << "退出預定。" << endl;
                break;
            }
            else if (choice == 'u') {
                cout << "請輸入新的預定人數:" << endl;
                cin >> num_people;

                if (num_people > remaining_capacity) {
                    cout << "更新後的預定人數仍超過剩餘容量。預定失敗。" << endl;
                    continue;
                }
            }
            else {
                cout << "無效輸入,請重新預約。" << endl;
                continue;
            }
        }

        // 更新剩餘容量並儲存資訊
        remaining_capacity -= num_people;
        audience_lst.emplace_back(nickname, contact, city, num_people);
        cout << "預約成功!當前剩餘容量: " << remaining_capacity << endl;

        // 停止條件
        cout << "是否繼續輸入?(輸入 'n' 停止,其他任意鍵繼續):" << endl;
        char stop;
        cin >> stop;
        if (stop == 'n') {
            break;
        }
    }
    int u = capacity - remaining_capacity;
    // 列印所有預約資訊
    cout << "截至目前,一共有" << u<< "位觀眾參與預約。預約聽眾資訊如下:"<< endl;
    for (const auto& audience : audience_lst) {
        audience.display();
    }

    return 0;
}

執行結果截圖:

任務7:

date.h:

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


date.cpp:

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


accumulator.h:

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


account.h:

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


account.cpp:

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

7_10.cpp:

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

執行結果截圖:

相關文章