c/c ++中何时通过引用传递和何时通过值传递 [英] when to pass by reference and when by value in c / c++

查看:38
本文介绍了c/c ++中何时通过引用传递和何时通过值传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
是否更好C++是按值传递还是按常量引用传递?
何时通过引用和什么时候在 C++ 中通过指针传递?

我对 c 和 c++ 相当陌生,我有以下关于将参数传递给函数的问题,我认为最好在这里提问并直接从大师那里获得知识的来源.

I am fairly new to c and c++ and I have the following question with regards to passing parameters to functions and thought it best to ask here and come straight to the source of the knowledge from the gurus.

什么时候应该按值传递参数,什么时候应该按引用传递?而现实世界中最常用的方法是什么?

When should I pass parameters by value and when sould they be passed by reference? And what is the most commonly used method in the real world?

提前致谢.

推荐答案

首选通过引用传递,通常是以下一项或多项:

Prefer pass by reference, usually one or more of:

  1. 如果它很大.(如果是 const,一定要这样做,尽管如此,还是要经常这样做,具体取决于此列表的其余部分)
  2. 如果您想对其进行编辑并使更改全局可见.
  3. 如果您希望虚函数具有多态行为.
  4. 在模板代码中,如果您不知道它将是什么类型.
  1. If it's big. (Definitely do this if it's const, do it anyway quite often though, depending on the rest of this list)
  2. If you want to edit it and make changes globally visible.
  3. If you want virtual functions to behave polymorphicly.
  4. In template code if you don't know what type(s) it's going to be.

传值:

  1. 如果它是一个简单的内置类型(例如 int)
  2. 如果您不希望更改更改原始对象.
  3. 如果您希望能够传入临时变量而不必使其成为常量.

这篇关于c/c ++中何时通过引用传递和何时通过值传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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