親クラス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;
}
!.eof()を使用しないでください。本当に悪いです –
string name; while(read_cash_file >> name){}はどうしますか?この場合、 –
は 'string name; getline(read_cash_file、name); '。またコンストラクタが必要な場合は0をデフォルトにします。 –