Class問題2 徵求c++高手,懂英文

(Account Class) Create a class called Account that a bank might use to represent customers' bank accounts. Your class should include one data member of type int to represent the account balance. Your class should provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it is greater than or equal to 0. If not, the balance should be set to 0 and the constructor should display an error message, indicating that the initial balance was invalid. The class should provide three member functions. Member function credit should add an amount to the current balance. Member function debit should withdraw money from the Account and should ensure that the debit amount does not exceed the Account's balance. If it does, the balance should be left unchanged and the function should print a message indicating "Debit amount exceeded account balance." Member function getBalance should return the current balance. Create a program that creates two Account objects and tests the member functions of class Account.

煩請高手大大幫忙!! 感謝!!

2 Answers

  • Wu
    Lv 5
    10 years ago
    Best Answer

    #include <iostream>

    using namespace std;

    class Account

    { private:

    int _balance;


    Account(int initvalue)

    { _balance = (initvalue >=0 ? initvalue : 0);

    if (initvalue < 0) cout << "Error: initial balance was invalid!" << endl;


    void credit(int amount)

    { if (amount > 0) _balance += amount;

    else cout << "Error: Credit amount was invalid!" << endl;


    void debit(int amount)

    { if (amount > 0)

    { if (_balance > amount) _balance -= amount;

    else cout << "Error: Debit amount exceeded account balance!" << endl;

    } else cout << "Error: Debit amount is invalid!" << endl;


    int getBalance() { return _balance; }


    int main()

    { Account a1(1000), a2(-1);

    cout << "balances are : " << a1.getBalance() << "," << a2.getBalance() << endl;;;

    cout << "balances are : " << a1.getBalance() << "," << a2.getBalance() << endl;



    cout << "balances are : " << a1.getBalance() << "," << a2.getBalance() << endl;


    return 0;


  • 10 years ago

    不要用 _ 當變數/函數 名稱的開頭!!

Still have questions? Get your answers by asking now.