如何获取返回值并将其设置为 "x" ?
How to take a returned value and set it to "x"?
我正在为学校做一些事情,但我遇到了一个问题。请理解我对 c++ 和编程非常陌生(过去的经验只是一点 HTML(。无论如何,这是我的问题。
例如,我是学校的学生,我想去吃午饭。我去吃午饭,然后花x大约钱,然后把这笔钱带回主要功能。
int lunch(int moneyL)
{
std::cout << Here is lunch! 4 bucks please";
moneyL - 4
return moneyL;
}
int main()
{
std::cout << "You are given 5 dollars to eat lunch" << std::endl;
int money = 5;
std::cout << "Lets go to lunch";
Lunch(money)
}
我的问题再次是(如果我感到困惑(我如何将 int main 中的钱设置为午餐中带走的钱?
谢谢
有多种方法可以解决此问题:
解决方案 1(按返回值(:
int lunch(int moneyL)
{
std::cout << "Here is lunch! 4 bucks pleasen";
moneyL = moneyL - 4;
return moneyL;
}
int main()
{
std::cout << "You are given 5 dollars to eat lunch" << std::endl;
int money = 5;
std::cout << "Lets go to lunchn";
money = lunch(money)
}
解决方案2(通过引用(:
void lunch(int& moneyL)
{
std::cout << "Here is lunch! 4 bucks pleasen";
moneyL = moneyL - 4;
}
int main()
{
std::cout << "You are given 5 dollars to eat lunch" << std::endl;
int money = 5;
std::cout << "Lets go to lunchn";
lunch(money);
}
您需要进行两项更改:
1(return moneyL - 4;
函数lunch
而不是该函数中的最后两行(这也修复了由于缺少;
而倒数第二行的语法错误(
2( money = Lunch(money)
main
,以便更新money
变量。(目前不是必需的,但将来会证明您的代码(。
C++中的函数参数按值传递。谷歌一下了解更多细节。展望未来,看看参考资料和指针:有适合你的替代公式,但我认为我给你的公式对初学者来说是最好的。
您需要通过引用传递值,这样:
#include <iostream>
void Lunch(int& moneyL)
{
std::cout << "Here is lunch! 4 bucks please" << std::endl;
moneyL -= 4; // another thing, this doesnt change anything unless it
// is coded as an assignation
// you dont need to return the value
}
int main()
{
std::cout << "You are given 5 dollars to eat lunch" << std::endl;
int money = 5;
std::cout << "Lets go to lunch" << std::endl;
Lunch(money);
std::cout << "Money now: " << money << std::endl;
}
我还没有读过你问的完整问题。我的建议是,你应该申报金钱和午餐作为学生班的数据成员。 像这样。
class Student{
public:
int money;
void lunch(){
//implementation of lunch goes here...
// subtract money here
}
};
int main(){
Student s;
s.money = 10;
s.lunch();
return 0;
}
最简单的解决方案是,正如πάντα ῥεῖ指出的那样,调用
money = Lunch(money);
而不是
Lunch(money);
另一种解决方案是,使函数采用"引用"而不是"值"作为参数:
void lunch(int& moneyL)
{
std::cout << Here is lunch! 4 bucks please";
moneyL -= 4;
}
在您的情况下,moneyL 的变量是 main(( 函数中 moneyL 的副本。在我的例子中,通过传递int&,lunch((中的moneyL与main((中的变量相同。因此,无需返回值。
提示:阅读"按值和引用传递的参数"一章:http://www.cplusplus.com/doc/tutorial/functions/
编辑:更正了"moneyL -= 4;",因为πάντα ῥεῖ在评论中写道。
- 如何获取进程以设置其亲和力?
- 如何获取控制面板设置值,如字体大小
- 获取和设置函数 c++
- 类中的 C++ int 被设置为值,似乎不知从何而来
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 在 C++ 中将函数获取和设置为虚拟函数
- Qt 原子 int 获取并立即设置
- 使用 c++ / QT 创建器从另一个类中设置和获取单例变量
- 如何直接从 FILETIME 结构获取/设置和获取秒数
- 如何在 C# 中设置或获取 DLL 库的参数?
- 如何使用C Win32 API设置和获取多个值(数组值)到Active Directory中的单个属性
- 在 c++ 中的区域语言设置下获取当前位置值
- C++元编程,使用switchcase设置和获取成员变量
- 从我的二维数组中设置和获取值时出错
- CRITICAL_SECTION用于设置和获取单个布尔值
- 在映射c++中,使用enum作为键来设置和获取值
- 设置和获取对象之间的变量而不引用它们
- C++动态数组和设置和获取函数
- 设置API获取设备属性
- 如何使用C++在tesseract中设置和获取变量