可能的重复:
指针变量和指针变量有什么区别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());
}
这篇关于通过指针&通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)