C++: Argument Passing quot;passed by referencequot;(C++:参数传递“通过引用传递)
问题描述
我理解与任何其他变量一样,参数的类型决定了参数与其自变量之间的交互.我的问题是,为什么要引用参数与为什么不引用的原因是什么?为什么有些函数参数引用,有些则不是?无法理解这样做的好处,有人可以解释一下吗?
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++:参数传递“通过引用传递"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++:参数传递“通过引用传递"


基础教程推荐
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 设计字符串本地化的最佳方法 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01