为什么会发生这种错误(C ++)?

时间:2014-02-11 05:54:30

标签: c++ class

我有一个名为SavingsAccount的类,其方法名为calculateMonthlyInterest。如果我安排这样的主要方法,它就可以正常工作,saver1的利息为60美元,saver2的利息为90美元:

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

1 个答案:

答案 0 :(得分:2)

以这种方式思考。你有一个平衡。现在你想让它成为每个账户的余额吗?或者您希望它为不同的帐户设置不同的值?

当然,您希望它在不同的帐户中进行更改。这意味着不同的帐户应该有不同的余额副本。您在代码中所做的是将其声明为引用并通过构造函数传递引用。当您接受并分配引用时,它不会将值从一个复制到另一个,而是指两个引用同一个对象(在这种情况下为balance)。现在,在初始化两者之后,如果更改main中的余额,则更改将反映在两个帐户中,因为它们具有的savingsBalance和main内部的余额基本上是相同的对象。

要更正它,请将int&amp; savingsBalance更改为int savingsBalance,并将SavingsAccount(int&amp; initialBalance)更改为SavingsAccount(int initialBalance)。这将使它接受存储在initialBalance中的值。