问题描述
在下面的call-by-value示例中,我不明白为什么这个代码不会将5的值更改为6.
In the following call-by-value example, I cannot understand why this code is not changing the value of the 5 to a 6.
第11行调用function changeValue的值为6,所以我会认为应该输出6,但仍然输出5。
Line 11 calls the function changeValue which has the value 6, so I would have thought 6 should be output, however 5 is still output?
#include <iostream>
using namespace std;
void changeValue(int value);
int main()
{
int value = 5;
changeValue(value);
cout << "The value is : " << value << "." << endl;
return 0;
}
void changeValue(int value)
{
value = 6;
}
// This doesn't change the value from 5 to 6. 5 is output?
推荐答案
当传递函数参数 by value 将对象的副本传递给函数而不是原始对象。无论你明确指定函数的参数,总是通过C / C ++中的值传递。
When you pass a function argument by value a copy of the object gets passed to the function and not the original object.Unless you specify explicitly arguments to functions are always passed by value in C/C++.
您的函数:
void changeValue(int value)
通过值接收参数,简单地是<$ c $>中的 value
$ c> main()创建并传递给函数,该函数对该值操作,而不是中的
。 值
> main()
receives the argument by value, in short a copy of value
in main()
is created and passed to the function, the function operates on that value and not the value
in main()
.
如果您要修改原文,则需要使用 传递参照。
If you want to modify the original then you need to use pass by reference.
void changeValue(int &value)
b $ b
现在,将对原始值
的引用(别名)传递给函数,函数对其进行操作,从而反映 main()
。
Now a reference(alias) to the original value
is passed to the function and function operates on it, thus reflecting back the changes in main()
.
这篇关于为什么call-by-value示例不修改输入参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!