[英]c++ trying to change local variable outside of function?
我得到了以下程序:
#include <iostream>
using namespace std;
// ### write myFunction() ###
// ###
int main(){
int x;
cin >> x;
myFunction(x);
cout << "The Number + 1 is " << x;
}
我知道我应该将 x 更改为 x++,但是当 x 是 main() 中的局部变量时,我该如何在 myFunction() 中这样做?
在 c++ 中,您可以通过reference
function 来传递变量,这意味着您将从 function 访问和写入实际变量,而不是变量的副本:
myFunction(x); // doesn't change
void myFunction(int& x) // note the "&" (it means that x is a "reference" to an int)
{
++x;
}
这篇文章很好地描述了“参考”的东西。
正如@0x5453 提到的,更好的方法是从指针返回递增的 integer 并将其分配给主变量,假设您被允许这样做。
x = myFunction(x);
int myFunction(int x)
{
return ++x;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.