我确定我忽略了一些非常基本的东西。如果有人可以提供一些帮助,或者指出我的相关主题,我将非常感激。此外,如果您需要更多我的代码,我很乐意提供它。
我有一个简单的银行账户计划。在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(&amp; 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变量。但是一旦函数结束,它就会恢复到初始值。
我确信这对于经验丰富的程序员来说非常重要。非常感谢您的见解。
谢谢, 亚当
答案 0 :(得分:3)
这是因为你通过值传递Bank而不是通过引用和const。改变
void deposit(const Bank bank, ofstream &outfile)
到
void deposit(Bank& bank, ofstream &outfile)
应该解决它