2014-02-11 111 views
0

我有一個名爲calculateMonthlyInterest的方法,名爲SavingsAccount。如果我安排我這樣的主要方法,它工作得很好,與具有$ 60的興趣saver1和saver2擁有$ 90的興趣:爲什麼會發生此錯誤(C++)?

void main() { 

    // create two savings account objects, then calculate interest for them 
    int balance = 200000; 
    SavingsAccount saver1(balance); 
    saver1.calculateMonthlyInterest(); 

    balance = 300000; 
    SavingsAccount saver2(balance); 
    saver2.calculateMonthlyInterest(); 
    cin.ignore(2); // keeps console from closing 
} 

但是,如果我安排一下這樣的,saver1和saver2都有興趣$ 90,儘管這是不正確的saver1:

void main() { 

    // create two savings account objects, then calculate interest for them 
    int balance = 200000; 
    SavingsAccount saver1(balance); 
    balance = 300000; 
    SavingsAccount saver2(balance); 

    saver1.calculateMonthlyInterest(); 
    saver2.calculateMonthlyInterest(); 
    cin.ignore(2); // keeps console from closing 
} 

很明顯,我可以通過設置它的第一種方式避免了錯誤,但我只是想知道這是爲什麼。無論哪種方式,它不應該爲saver1和saver2對象傳遞不同的值,還是我錯過了某些東西?

編輯:下面是計劃爲那些誰希望看到它的其餘部分:

#include <iostream> 
using namespace std; 

class SavingsAccount { 
public: 
    SavingsAccount(int& initialBalance) : savingsBalance(initialBalance) {} 

    // perform interest calculation 
    void calculateMonthlyInterest() { 

    /*since I am only calculating interest over one year, the time does not need to be 
    entered into the equation. However, it does need to be divided by 100 in order to 
    show the amount in dollars instead of cents. The same when showing the initial 
    balance */ 

     interest = (float) savingsBalance * annualInterestRate/100; 
     cout << "The annual interest of an account with $" << (float)savingsBalance/100 << " in it is $" << interest << endl; 
    }; 

    void setAnnualInterestRate(float interestRate) {annualInterestRate = interestRate;} // interest constructor 

    int getBalance() const {return savingsBalance;} // balance contructor 

private: 
    static float annualInterestRate; 
    int& savingsBalance; 
    float interest; 
}; 

float SavingsAccount::annualInterestRate = .03; // set interest to 3 percent 
+8

你能告訴我們你的SavingAccount類的定義嗎? –

+3

我的賭注是'SavingsAccount'存儲傳遞給它的引用。 –

+0

我猜的餘額是存儲在'SavingsAccount'中的一個靜態? – John3136

回答

2

想想這樣。你有一個平衡點。現在你想讓它成爲每個賬戶的餘額嗎?或者你希望它對不同的賬戶有不同的價值?

當然,你希望它改變在不同的帳戶。這意味着不同的賬戶應該有不同的餘額副本。你在代碼中做的是將它聲明爲引用並通過構造函數傳遞引用。當你接受和分配引用時,它不會將值從一個拷貝到另一個,而是使兩個引用同一個對象(在本例中爲balance)。現在,在初始化兩者後,如果您更改主要餘額,則更改將反映在兩個帳戶中,因爲它們具有的儲蓄餘額和主內部的餘額基本上是相同的對象。

要更正此問題,請將int & savingsBalance更改爲int savingsBalance,並將SavingsAccount(int & initialBalance)更改爲SavingsAccount(int initialBalance)。這將使它接受initialBalance中存儲的值。

+0

這就是大衛評論後我所懷疑的。謝謝您的幫助! – user2302019

相關問題