当我写Func1(int&a)和Func1(int*a)时有什么区别

Sim*_*ons 12 c++ windows parameter-passing pass-by-reference

可能重复:
C++中指针变量和引用变量之间的差异

当我开始使用C++时,我发现下面的操作令人困惑.我知道通过引用传递和传递值.但是最近我遇到了这样的功能让我很困惑:

Func1(int &a) 
Func2(int *a)
Run Code Online (Sandbox Code Playgroud)

这两个函数都期望a的地址,但是当我调用Func1时,我会这样做,Func1(a)而在Func2的情况下,我调用了Func2(&a)

为什么Func1在期望a的地址时直接接受int a

Chu*_*dad 10

Func1(int &a) 
// accepts arguments by reference.
// changes to a inside Func1 is reflected in the caller
// a cannot bind to an Rvalue e.g. can't call Func1(5)
// a can never be referring to something that is not a valid object

Func2(int *a)
// accept arguments by value
// change to a inside Func1 not reflected in caller, changes to *a are
// a can bind to an Rvalue e.g. Func1(&localvar)
// a can be NULL. Hence Func2 may need to check if a is NULL
Run Code Online (Sandbox Code Playgroud)


Nat*_*man 6

为pass-by-reference参数提供参数时,编译器将在后台执行必要的操作.作为程序员,您知道它在内部使用您的参数的地址,但这隐藏在传递引用抽象中.这比使用指针更安全,因为您无法无意中重新分配引用.


Ebo*_*ike 5

内部来说,没有太大区别。但一个是引用,另一个是指针。主要区别在于您无法修改函数中的引用,因此引用将始终指向a.

IE,

void func1(int &a) {
    a = 5;
}
Run Code Online (Sandbox Code Playgroud)

这将修改a,即调用者指向的任何变量。

void func2(int *a) {
    *a = 5;   // Same effect as the above code
    a = &b;   // You couldn't do that with a reference
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

14286 次

最近记录:

14 年,9 月 前