我理解与任何其他变量一样,参数的类型决定了参数与其自变量之间的交互.我的问题是,为什么要引用参数与为什么不引用的原因是什么?为什么有些函数参数引用,有些则不是?无法理解这样做的好处,有人可以解释一下吗?
I understand as with any other variable, the type of a parameter determines the interaction between the parameter and its argument. My question is that what is the reasoning behind why you would reference a parameter vs why you wouldn't? Why are some functions parameters reference and some are not? Having trouble understanding the advantages of doing so, could someone explain?
引用传递的能力存在有两个原因:
The ability to pass by reference exists for two reasons:
修改参数的例子
void get5and6(int *f, int *s) // using pointers
{
*f = 5;
*s = 6;
}
这可以用作:
int f = 0, s = 0;
get5and6(&f,&s); // f & s will now be 5 & 6
或
void get5and6(int &f, int &s) // using references
{
f = 5;
s = 6;
}
这可以用作:
int f = 0, s = 0;
get5and6(f,s); // f & s will now be 5 & 6
当我们通过引用传递时,我们传递的是变量的地址.按引用传递类似于传递指针 - 在两种情况下都只传递地址.
When we pass by reference, we pass the address of the variable. Passing by reference is similar to passing a pointer - only the address is passed in both cases.
例如:
void SaveGame(GameState& gameState)
{
gameState.update();
gameState.saveToFile("save.sav");
}
GameState gs;
SaveGame(gs)
或
void SaveGame(GameState* gameState)
{
gameState->update();
gameState->saveToFile("save.sav");
}
GameState gs;
SaveGame(&gs);
<小时>由于只传递地址,变量的值(对于巨大的对象可能非常大)不需要复制.因此,通过引用传递可以提高性能,尤其是在以下情况下:
另外,阅读 const
参考资料.使用时不能在函数中修改参数.
Also, read on const
references. When it's used, the argument cannot be modified in the function.
这篇关于C++:参数传递“通过引用传递"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!