2012-03-17 144 views
0

我确定我忽略了一些非常基本的东西。如果任何人都可以提供帮助,或者指向相关主题,我会非常感激。另外,如果你需要更多的代码,我很乐意提供它。C++在类之间传递对象

我有一个简单的银行账户程序。在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变量。但是一旦函数结束,它就会恢复到初始值。

我相信这对于更有经验的程序员来说是最基本的。非常感谢您的洞察力。

感谢, 亚当

回答

3

这是因为你逝去的银行按值而不是按引用和常量。更改

void deposit(const Bank bank, ofstream &outfile) 

void deposit(Bank& bank, ofstream &outfile) 

应该修复它

+0

出于某种原因,仍然是没有做的伎俩。然而,我看到大家都同意你的回答,这让我觉得问题在我的最后。还有其他建议吗? – 2012-03-17 23:07:27

+0

符合:bank.getAccount(index)是通过引用,指针或值返回的帐户? – 2012-03-17 23:10:17

+0

我认为这是通过引用返回的。这里的实现: – 2012-03-17 23:14:45