调用方法不会更改值,除非从方法本身内部调用
calling a method wont change the value unless from within the method itself
我试图找出我的错误。
我正在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){
相关文章:
- 在c++中多次调用方法
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 接收字符串并使用它来调用方法C++
- 使用 gmock c++ 在真实对象上调用方法
- 不带预处理器的调用方法/文件的文件名/行号
- JNI从Android调用C++方法
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何使用接口指针调用方法,该指针是其具体类的一部分,而不是接口的一部分
- 从内部类中的方法从包含类调用方法
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 为什么派生类的实例从基类调用方法?
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- C++当您取消引用指向类对象的指针,然后将其作为引用返回时,是否可以对此引用调用方法
- 通过模板函数对未知类型调用方法
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 创建一个C++DLL以从C#DLL调用方法
- 如何从qt中的类中调用方法
- 如何在不迭代的情况下对数组中的每个元素调用方法
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- C ++:如何在不创建对象的情况下在主函数中调用方法