在C和C ++中通过引用传递的含义? [英] Meaning of pass by reference in C and C++?

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

问题描述

我对C和C ++中的按引用传递的含义感到困惑。



在C中,没有引用。所以我想按引用传递意味着传递指针。但是为什么不叫它通过指针传递呢?



在C ++中,我们既有指针又有引用(还有类似迭代器的东西)。那么通过引用传递在这里是什么意思?

解决方案

在通俗用法中,通过引用传递意味着,如果被叫方修改了它的参数会影响调用方,因为被调用方看到的参数将引用调用方看到的值。





在C ++中,按引用调用



em>可以使用引用指针来完成。在C语言中,按引用调用只能通过传递指针来实现。



按值调用:

  void foo(int x)
{
// x是调用foo()的变量的*副本*
x = 42;
}

int main()
{
int a = 0;
foo(a);
//此时,a == 0
}

通话通过引用,C样式:

  void foo(int * x)
{
// x仍然是foo()参数的*副本*,但是该副本***
//调用者看到的值
* x = 42;
}

int main()
{
int a = 0;
foo(& a);
//此时,a == 42
}

严格来说, C中没有通过引用。您要么传递变量按值,要么传递指向该变量按值的指针。


I am confused about the meaning of "pass by reference" in C and C++.

In C, there are no references. So I guess pass by reference means passing a pointer. But then why not call it pass by pointer?

In C++, we have both pointers and references (and stuff like iterators that lies close). So what does pass by reference mean here?

解决方案

In colloquial usage, "pass by reference" means that, if the callee modifies its arguments, it affects the caller, because the argument as seen by the callee refers to the value as seen by the caller.

The phrase is used independent of the actual programming language, and how it calls things (pointers, references, whatever).

In C++, call-by-reference can be done with references or pointers. In C, call-by-reference can only be achieved by passing a pointer.

"Call by value":

void foo( int x )
{
    // x is a *copy* of whatever argument foo() was called with
    x = 42;
}

int main()
{
    int a = 0;
    foo( a );
    // at this point, a == 0
}

"Call by reference", C style:

void foo( int * x )
{
    // x is still a *copy* of foo()'s argument, but that copy *refers* to
    // the value as seen by the caller
    *x = 42;
}

int main()
{
    int a = 0;
    foo( &a );
    // at this point, a == 42
}

So, strictly speaking, there is no pass-by-reference in C. You either pass the variable by-value, or you pass a pointer to that variable by-value.

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

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