C++:参数传递“通过引用传递" [英] C++: Argument Passing "passed by reference"

查看:32
本文介绍了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:

  1. 修改函数参数的值
  2. 为了避免出于性能原因复制对象

修改参数的例子

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:

  1. 传递给函数的对象很大(我会在这里使用指针变量,以便调用者知道函数可能会修改变量的值)
  2. 该函数可以被多次调用(例如在循环中)

另外,阅读 const 参考资料.使用时不能在函数中修改参数.

Also, read on const references. When it's used, the argument cannot be modified in the function.

这篇关于C++:参数传递“通过引用传递"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆