问题描述
我理解与任何其他变量一样,参数的类型决定了参数与其自变量之间的交互.我的问题是,为什么要引用参数与为什么不引用的原因是什么?为什么有些函数参数引用,有些则不是?无法理解这样做的好处,有人可以解释一下吗?
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);
<小时>由于只传递地址,变量的值(对于巨大的对象可能非常大)不需要复制.因此,通过引用传递可以提高性能,尤其是在以下情况下:
Since only the address is being passed, the value of the variable (which could be really huge for huge objects) doesn't need to be copied. So passing by reference improves performance especially when:
- 传递给函数的对象很大(我会在这里使用指针变量,以便调用者知道函数可能会修改变量的值)
- 该函数可以被多次调用(例如在循环中)
另外,阅读 const 参考资料.使用时不能在函数中修改参数.
Also, read on const references. When it's used, the argument cannot be modified in the function.
这篇关于C++:参数传递“通过引用传递"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)