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