Pass by pointer amp; Pass by reference(通过指针amp;通过引用传递)
问题描述
可能的重复:
指针变量和指针变量有什么区别C++中的引用变量?
路过有好处吗在 C++ 中通过引用传递指针?
在这两种情况下,我都达到了结果.那么什么时候一个比另一个更受欢迎呢?我们使用一个而不是另一个的原因是什么?
In both cases, I achieved the result. So when is one preferred over the other? What are the reasons we use one over the other?
#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
int z = *x;
*x=*y;
*y=z;
}
void swap(int& x, int& y)
{
int z = x;
x=y;
y=z;
}
int main()
{
int a = 45;
int b = 35;
cout<<"Before Swap
";
cout<<"a="<<a<<" b="<<b<<"
";
swap(&a,&b);
cout<<"After Swap with pass by pointer
";
cout<<"a="<<a<<" b="<<b<<"
";
swap(a,b);
cout<<"After Swap with pass by reference
";
cout<<"a="<<a<<" b="<<b<<"
";
}
输出
Before Swap
a=45 b=35
After Swap with pass by pointer
a=35 b=45
After Swap with pass by reference
a=45 b=35
推荐答案
引用在语义上如下:
T&<=>*(T * const)
const T&<=>*(T const * const)
T&&<=>[无 C 等价物]
(C++11)
与其他答案一样,C++ 常见问题解答中的以下内容是单行答案:可能时引用,需要时使用指针.
As with other answers, the following from the C++ FAQ is the one-line answer: references when possible, pointers when needed.
优于指针的一个优点是您需要显式转换才能传递 NULL.不过还是有可能的.在我测试过的编译器中,没有一个会发出以下警告:
An advantage over pointers is that you need explicit casting in order to pass NULL. It's still possible, though. Of the compilers I've tested, none emit a warning for the following:
int* p() {
return 0;
}
void x(int& y) {
y = 1;
}
int main() {
x(*p());
}
这篇关于通过指针&通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过指针&通过引用传递


基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01