我想弄清楚我的錯誤。調用方法將不會更改值,除非從方法本身內
我在C++中,那裏有像credit()
,debit()
等
我寫了一個transfer()
方法,我得到這個問題的一些方法上Account
類的工作是,它需要「錢」出帳a1
,但不計入a2
。但是,如果我在account.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;
}
}
很好,謝謝,它的工作原理。所以根據我的理解,當我打電話給a1.transfer(a2,13)時,它製作了a2的拷貝,並沒有改變原始的a2?因此使用參考將其顯示到正確的位置,並將結果設置在正確的位置?還在習慣它。 –
@AuRis你是正確的,通過價值傳遞和改變一個副本,而通過參考傳遞可以讓你「就地」改變項目。 – dasblinkenlight