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

标签 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

最佳答案

这样想。你有平衡。现在你想让它成为每个账户的余额吗?还是您希望它对不同的帐户具有不同的值?

当然,您希望它在不同的帐户中发生变化。这意味着不同的账户应该有不同的余额拷贝。您在代码中所做的是将其声明为引用并通过构造函数传递引用。当您接受和分配引用时,它不会将值从一个复制到另一个,而是使两者都引用同一个对象(在本例中为 balance)。现在,在初始化两者之后,如果更改 main 中的余额,则更改将反射(reflect)在两个帐户中,因为它们拥有的 savingsBalance 和 main 中的余额本质上是相同的对象。

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

关于c++ - 为什么会发生此错误(C++)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21694207/

相关文章:

C++ - 从类模板调用方法

c++ - 何时在TriCore模拟器中加载操作数?

c++ - 如何将 RotatedRect 中的所有像素存储到另一个矩阵?

c++ - 为什么我会重新定义类错误?

java - java 类在同一个包中找不到其他类

c++ - 在 C++ 中计算有序集的并集

c++ - 返回 C++ std::string 对象是否可以避免内存泄漏?

php - 使用 PHP Reflection 获取非静态的公共(public)属性

javascript - 变量没有在 php 中相乘

c++ - 用于搜索数字和字符串的高效数据结构