我已经在函数(int main)中声明了一个变量,然后当我操纵该变量的值不会改变函数(int main)中的某个位时,我在函数(void)中创建了一个语句。如果我所做的语句位于不同的函数中,该如何操作该变量?
这是我的代码。
#include <iostream>
#include <cstdlib>
using namespace std;
void shoppingList (int money, int userChoice)
{
cout<<"1. Apples for 20$"
<<"\n2. Oranges for 30$"
<<"\n\nChoice: ";
cin>>userChoice;
if (userChoice == 1)
{
money = money - 20;
cout<<"20$ had been deducted ";
cout<<"\nMoney: "<<money<<endl;
}
if (userChoice == 2)
{
money = money - 30;
cout<<"30$ had been deducted ";
cout<<"\nMoney: "<<money<<endl;
}
}
int main()
{
int userChoice;
int money = 500;
while (true)
{
char choices[2];
cout<<"Money: "<<money<<"\n\n"<<endl;
cout<<"1. Draw some Numbers"
<<"\n2. Exit"
<<"\n\nChoice: ";
cin>>choices;
if (choices[0] == '1')
{
system ("CLS");
shoppingList (money ,userChoice);
system ("PAUSE");
system ("CLS");
}
else if (choices[0] == '2')
{
return 0;
}
else if (choices[0] > '2' || choices[0] < '1')
{
cout<<"\nInvalid Input\nPLs try again"<<endl;
system ("PAUSE");
system ("CLS");
}
else
{
cout<<"\nInvalid Input\nPLs try again"<<endl;
system ("PAUSE");
system ("CLS");
}
}
}
如果还有其他错误或改进的方法,请告诉我如何做。预先感谢
答案 0 :(得分:2)
以下是一些观察结果,
情况1:在下面的快照中,money
中的快照userChoice
和shoppingList ()
具有局部范围,因此该变量的任何更改都不会反映在调用方法中
void shoppingList (int money, int userChoice) { /* catch by value */
}
int main(void) {
shoppingList (money ,userChoice);
return 0;
}
如果我所做的语句位于其他函数中,该如何操作该变量?使用引用变量而不是按值传递。对于例如
/* catch by references */
void shoppingList (int &money, int &userChoice) { /* this money is reference of money
declared in main(), so any change
with money in this API will reflect
in main() */
}
int main(void) {
shoppingList (money ,userChoice);
return 0;
}
在上述情况下,您通过main()
函数传递了money
并使用参考变量进行捕获,即在money
中没有为shoppingList ()
创建新的内存money
即具有相同的存储位置,因此,如果您在userchoice
方法中使用shoppingList()
和main()
进行任何更改,则会在persons
函数中得到反映。 / p>