我目前正在学习c ++并试图制造自动售货机!我知道我的代码确实很糟糕,对此我感到抱歉。
我正在尝试建立一家银行并让用户从中借钱,唯一的问题是银行无法向用户增加资金。这是我的代码。

void Bank::askLoan() {
//ColaMachine object
ColaMachine cola;

bool loanGranted = false;

cout << string(100, '\n');
cout << "You do not have enough money!\n\n";
cout << "Would you like to take a loan?\n\n(1)-Yes\n(2)-No\n\n\n";
int choice;
cin >> choice;

switch (choice) {
case 1:
    //Print the bank menu!

    printBank();
    while (loanGranted != true) {
        cout << "Enter the amount to lend: $";
        cin >> _loanValue;
        //Test if _loanValue is less than or = to bankmoney, so they would scam the bank.
        if (_loanValue <= _bankMoney) {
            //Supposed to add money to the user.
            cola.addMoney(_loanValue);
            break;
        }
        else {
            cout << "You entered too much! Try again..." << endl;
        }
    }
    break;
case 2:
    //User does not want to take a loan! Quit the game!
    //Not implemented, yet.
    break;
default:
    cout << "Bad input! Please retry..." << endl;
}


}

如果输入的数量在正确的范围内,则从ColaMachine类调用addMoney()Func。

void ColaMachine::addMoney(int money) {

//This part doesnt seem to modify the actual value
//Whenever It goes back to the main game loop it doesnt change.
_money += money;


}

据我了解,+ =与_money = _money + money相同;

我在这里做错了什么?
完整源代码在GitHub-
https://github.com/Rohukas/-LearningCPP

最佳答案

问题在于您正在askLoan()方法内创建新的可乐对象,该对象在函数末尾被销毁,因此对addMoney()方法的调用会修改该临时可乐对象的状态。一种选择是通过指向askLoan()方法的指针来提供可乐对象。
例如,在ColaMachine::chooseDrink()中,您将调用bo.askLoan(this)this是指向您从中调用bo.askLoan()的对象的指针。
您需要修改您的askLoan()签名:
void askLoan(ColaMachine * cola)并从ColaMachine cola;本身中删除askLoan()

10-04 16:32