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

问题描述:

我有一个名为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

想想这样。你有一个平衡点。现在你想让它成为每个账户的余额吗?或者你希望它对不同的账户有不同的价值?

当然,你希望它改变在不同的帐户。这意味着不同的账户应该有不同的余额副本。你在代码中做的是将它声明为引用并通过构造函数传递引用。当你接受和分配引用时,它不会将值从一个拷贝到另一个,而是使两个引用同一个对象(在本例中为balance)。现在,在初始化两者后,如果您更改主要余额,则更改将反映在两个帐户中,因为它们具有的储蓄余额和主内部的余额基本上是相同的对象。

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

+0

这就是大卫评论后我所怀疑的。谢谢您的帮助! – user2302019