C ++通过值或引用传递对象? [英] Does C++ pass objects by value or reference?

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

问题描述

一个简单的问题,我在这里找不到答案。



我理解的是,在调用期间传递一个参数到函数, p>

  void myFunction(type myVariable)
{
}

void main
{
myFunction(myVariable);
}

对于简单数据类型,例如 int

但是如果 float myVariable 是一个数组,只传递起始地址(即使我们的函数是一个值函数调用)。



如果 myVariable 是一个对象,也只传递对象的地址,而不是创建一个副本并传递它。



到问题。 C ++通过引用或值传递对象?

解决方案

参数通过值传递,除非函数签名另外指定: p>


  • void foo(type arg) arg 是一个简单类型,一个指针类型或一个类类型,而不管类型是否通过值传递

  • < void foo(type& arg) arg 通过引用传递。


在数组的情况下,传递的值是指向数组的第一个元素的指针。如果你知道编译时数组的大小,你也可以通过引用传递数组: void foo(type(& arg)[10]) / p>

A simple question for which I couldn't find the answer here.

What I understand is that while passing an argument to a function during call, e.g.

void myFunction(type myVariable)
{
}

void main()
{
    myFunction(myVariable);
}

For simple datatypes like int, float, etc. the function is called by value.

But if myVariable is an array, only the starting address is passed (even though our function is a call by value function).

If myVariable is an object, also only the address of the object is passed rather than creating a copy and passing it.

So back to the question. Does C++ pass a object by reference or value?

解决方案

Arguments are passed by value, unless the function signature specifies otherwise:

  • in void foo(type arg), arg is passed by value regardless of whether type is a simple type, a pointer type or a class type,
  • in void foo(type& arg), arg is passed by reference.

In case of arrays, the value that is passed is a pointer to the first elements of the array. If you know the size of the array at compile time, you can pass an array by reference as well: void foo(type (&arg)[10]).

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

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