调用方法不会更改值,除非从方法本身内部调用

calling a method wont change the value unless from within the method itself

本文关键字:调用 方法 内部      更新时间:2023-10-16

我试图找出我的错误。

我正在C++Account类,其中有一些方法,如credit()debit()等。
我写了一个transfer()的方法,我得到的问题是它从a1考虑"钱"中取出,但没有记入a2。但是,如果我在帐户中的方法本身中打印它.cpp它确实会显示正确的结果,而总的来说,余额保持不变。

你能看出我的错误吗?与参考、指针等有关?
这是主要的:

a1.println(); 
a2.println();
cout<< "Valid parameter " << endl;
cout<< a1.transfer(a2, 13) << endl;
a1.println();
a2.println();

这是它打印的内容:

(Account(65,140))
(Account(130,100))
Valid parameter 
1
(Account(65,127))
(Account(130,100))

以下是方法的定义:

    // withdraw money from account
    bool Account::debit(int amount){
    if (amount>=0 && balance>=amount) {
        balance=balance-amount; // new balance
        return true;
    } else {
        return false;
    }
}

// deposit money
bool Account::credit(int amount){
    if (amount>=0) {
        balance=balance+amount; // new balance
        return true;
    } else {
        return false;
    }
}
bool Account::transfer(Account other, int amount){
    if (amount>=0 && balance>=amount) {
        debit(amount);
        other.credit(amount);
        //other.println();// prints corect amount
        return true;
    } else {
        return false;
    }
}

这是因为您正在按值传递其他Account。余额可以正常更改,但在帐户的不同实例上,这意味着副本被修改,而原始副本保持不变。

将代码更改为通过引用传递Account以使其正常工作。

bool Account::transfer(Account& other, int amount)
//                            ^
//                           HERE

您没有通过引用传递"其他"

 bool Account::transfer(Account& other, int amount){