gpt4 book ai didi

c++ - 添加到私有(private)变量不起作用

转载 作者:行者123 更新时间:2023-11-28 01:37:22 25 4
gpt4 key购买 nike

我目前正在学习 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() 函数。

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) 并从 askLoan() 本身中删除 ColaMachine cola;

关于c++ - 添加到私有(private)变量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48682805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com