无法初始化构造函数

时间:2017-12-05 00:30:43

标签: c++ file-processing

我正在创建一个包含父类Account和派生类BankAccount的程序。最初,我必须将帐户余额设置为5000.当进行某些交易时,应更新此余额。此外,每当程序关闭时,程序应返回最新的余额。以下是我的代码。但是,我无法正确初始化构造函数,因此,初始平衡永远不会正确设置。请告诉我我做错了什么。

 class Account
{
public:


    void setCashBal(); //updates the cash balance in account whenever a transaction is made
    double getCashBal(); //retrieves recent cash balance


protected:
    double cash_balance;
};


void Account::setCashBal()
{

    double initial_bal;


    ifstream read_cash_file("cash_bal_file.txt", ios_base::in);

    int count = 0;

    if (read_cash_file.is_open()) //check whether the file could be openend
    {

        while (!(read_cash_file.eof())) //reading until the end of file
        {
            count = count + 1;
            break;
        }
        read_cash_file.close();

        if (count == 0)//if the file is opened the first time, initial cash balance is 5000
        {
            initial_bal = 5000;

            ofstream write_cash_file("cash_bal_file.txt", ios::out);


            write_cash_file << initial_bal; //writing the initial value of cash balance in cash_bal_file
            write_cash_file.close();

            read_cash_file.open("cash_bal_file.txt", ios_base::in); 
            read_cash_file >> cash_balance;
            read_cash_file.close();
        }


        else //getting the latest cash balance
        {
            read_cash_file.open("cash_bal_file.txt", ios::in);
            read_cash_file >> cash_balance;
            read_cash_file.close();
        }
    }

    else //case when the file could not be openend
        cout << endl << "Sorry, cash_bal_file could not be opened." << endl;
}

double Account::getCashBal()
{
    return cash_balance;
}


    class BankAccount :public Account
    {
    public:
        BankAccount();
        void viewBalance();
    };

    BankAccount::BankAccount()

    {
        setCashBal();
        cash_balance = getCashBal();
    }


    void BankAccount::viewBalance()
    {

        double balance;
        ifstream view_bal("cash_bal_file.txt", ios_base::in); //getting the latest cash_balance from cash_bal_file.
        view_bal >> balance;


        cout << endl << "The balance in your bank account is " << balance << endl;
    }


    int main()
    {
        BankAccount bnkObj;
        bnkObj.viewBalance();

    return 0;
    }

1 个答案:

答案 0 :(得分:0)

class Account
{
  public:
    int n;

    Account(): n(5000)
    {}
};

这称为“在构造函数中初始化成员变量”,或者只是“初始化”。如果您在介绍性的C ++文本中搜索“初始化”,您会发现类似的内容。