我有一個名爲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
你能告訴我們你的SavingAccount類的定義嗎? –
我的賭注是'SavingsAccount'存儲傳遞給它的引用。 –
我猜的餘額是存儲在'SavingsAccount'中的一個靜態? – John3136