我写 Func1(int &a) 和 Func1(int \*a) 有什么区别?

新手上路,请多包涵

可能重复:

C++中指针变量和引用变量的区别

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

 Func1(int &a)
Func2(int *a)

这两个函数都需要 a 的地址,但是当我调用 Func1 时,我通过 Func1(a) 来执行此操作,如果是 Func2,我通过 Func2(&a) 调用。

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

原文由 Simsons 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 477
2 个回答
Func1(int &a)
// It accepts arguments by reference.
// Changes to an inside Func1 are reflected in the caller.
// 'a' cannot bind to an Rvalue, e.g., it can't call Func1(5)
// 'a' can never be referring to something that is not a valid object

Func2(int *a)
// It accepts arguments by value.
// Change to an inside Func1 is not reflected in the caller, and 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.

原文由 Chubsdad 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

原文由 asdfjklqwer 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题