1 条题解

  • 0
    @ 2020-03-26 21:39:06

    之前的代码,也是加上virtual修改一下main函数即可

    #include<iostream>
    #include<iomanip>
    #include<string>
    #include<vector>
    using namespace std;
    
    class Account
    {
    protected:
        double balance;
    public:
        void setBalance(double v) { balance = v; }
        double getBalance() { return balance; }
        Account(double v = 0.0) :balance(v) {}
        virtual bool credit(double val) { balance += val; return true; }
        virtual bool debit(double val) {
            if (balance >= val) return (balance -= val, true);
            else return (cout << "Debit amount exceeded account balance.\n", false);
        }
        bool check() { return balance >= 0; }
        virtual double calculateInterest() { return 0; }
    };
    
    class CheckingAccount : public Account
    {
    private:
        double ff;
    public:
        CheckingAccount(double v = 0.0, double f = 0.0) : ff(f) { balance = v; }
        virtual bool credit(double v) {
            if (balance + v - ff >= 0) return (balance += v - ff, true);
            else return (cout << "Operation not permitted.\n", false);
        }
        virtual bool debit(double v) {
            if (balance >= v + ff) return balance -= v + ff, true;
            else return (cout << "Operation not permitted.\n", false);
        }
    };
    
    class SavingAccount : public Account
    {
    private:
        double ra;
    public:
        SavingAccount(double v, double r) :ra(r) { balance = v; }
        using Account::credit;
        using Account::debit;
        double calculateInterest() { return balance += balance * ra / 100.0; }
    };
    
    vector<Account*> ac;
    int main() {
        int n;
        int t;
        double  tmp, inp, outp;
        cin >> n;
        for (int i = 0; i < n; i++)
        {
            cin >> t >> tmp >> inp >> outp;
            if (t) ac.push_back(new CheckingAccount(10000.0, tmp));
            else ac.push_back(new SavingAccount(10000.0, tmp));
            ac[i]->calculateInterest();
            ac[i]->credit(inp);
            ac[i]->debit(outp);
        }
        for (int i = 0; i < n; i++)
        {
            cout << fixed << setprecision(3) << ac[i]->getBalance() << endl;
        }
        return 0;
    }
    
    
  • 1

12.14 Polymorphic Banking Program Using Account Hierarchy

信息

ID
1009
难度
1
分类
(无)
标签
递交数
89
已通过
39
通过率
44%
上传者