我确定我会忽略一些非常基本的内容。如果有人可以提供帮助或将我指向相关主题,我将非常感谢。另外,如果您需要更多我的代码,我很乐意提供。
我有一个简单的银行帐户计划。在main()类中,我具有以下功能:
void deposit(const Bank bank, ofstream &outfile)
{
int requested_account, index;
double amount_to_deposit;
const Account *account;
cout << endl << "Enter the account number: "; //prompt for account number
cin >> requested_account;
index = findAccount(bank, requested_account);
if (index == -1) //invalid account
{
outfile << endl << "Transaction Requested: Deposit" << endl;
outfile << "Error: Account number " << requested_account << " does not exist" << endl;
}
else //valid account
{
cout << "Enter amount to deposit: "; //prompt for amount to deposit
cin >> amount_to_deposit;
if (amount_to_deposit <= 0.00) //invalid amount to deposit
{
outfile << endl << "Transaction Requested: Deposit" << endl;
outfile << "Account Number: " << requested_account << endl;
outfile << "Error: " << amount_to_deposit << " is an invalid amount" << endl;
}
else //valid deposit
{
outfile << endl << "Transaction Requested: Deposit" << endl;
outfile << "Account Number: " << requested_account << endl;
outfile << "Old Balance: $" << bank.getAccount(index).getAccountBalance() << endl;
outfile << "Amount to Deposit: $" << amount_to_deposit << endl;
bank.getAccount(index).makeDeposit(&amount_to_deposit); //make the deposit
outfile << "New Balance: $" << bank.getAccount(index).getAccountBalance() << endl;
}
}
return;
} // close deposit()
问题在于makeDeposit(&amount_to_deposit)。输出文件显示:
Transaction Requested: Deposit
Account Number: 1234
Old Balance: $1000.00
Amount to Deposit: $168.00
New Balance: $1000.00
在Account类中,以下是makeDeposit函数:
void Account::makeDeposit(double *deposit)
{
cout << "Account balance: " << accountBalance << endl;
accountBalance += (*deposit);
cout << "Running makeDeposit of " << *deposit << endl;
cout << "Account balance: " << accountBalance << endl;
return;
}
来自cout调用的控制台输出为:
Enter the account number: 1234
Enter amount to deposit: 169
Account balance: 1000
Running makeDeposit of 169
Account balance: 1169
因此,在makeDeposit()函数中,它可以正确更新accountBalance变量。但是一旦函数结束,它将恢复为初始值。
我确信这对经验丰富的程序员是基本的。您的见解将不胜感激。
谢谢,
亚当
最佳答案
这是因为您是按值传递银行,而不是按引用传递常量。改变中
void deposit(const Bank bank, ofstream &outfile)
至
void deposit(Bank& bank, ofstream &outfile)
应该修复它