2012-03-17 145 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