我有一个名为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发布于 2014-02-11 06:20:14
就这么想吧。你有一个平衡。现在你想让它成为每个帐户的余额吗?还是您希望它对不同的帐户具有不同的值?
当然,你希望它在不同的帐户中改变。这意味着不同的帐户应该有不同的副本的余额。您在代码中所做的是将其声明为引用并通过构造函数传递引用。当您接受和赋值引用时,它不会将值从一个复制到另一个,而是同时引用同一个对象(在本例中为balance)。现在,在您将两者都弱化之后,如果更改main中的余额,则更改将反映在两个帐户中,因为它们拥有的savingsBalance和main内部的余额本质上是相同的对象。
要纠正它,请将int &savingsBalance更改为int savingsBalance,并将SavingsAccount(int& initialBalance)更改为SavingsAccount(int initialBalance)。这将使它接受存储在initialBalance中的值。
https://stackoverflow.com/questions/21694207
复制相似问题