Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
Are there benefits of passing by pointer over passing by reference in C++?
在这两种情况下,我都取得了结果。 那么什么时候比另一个更受欢迎呢?我们使用其中一种的原因是什么?
#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\n";
cout<<"a="<<a<<" b="<<b<<"\n";
swap(&a,&b);
cout<<"After Swap with pass by pointer\n";
cout<<"a="<<a<<" b="<<b<<"\n";
swap(a,b);
cout<<"After Swap with pass by reference\n";
cout<<"a="<<a<<" b="<<b<<"\n";
}
输出
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&& <=> [no C equivalent]
(C++11)
与其他答案一样,C++ 常见问题解答中的以下内容是单行答案:尽可能引用,需要时提供指针。
优于指针的一个优点是您需要显式转换才能传递 NULL。 不过,这仍然是可能的。 在我测试过的编译器中,没有一个会发出以下警告:
int* p() {
return 0;
}
void x(int& y) {
y = 1;
}
int main() {
x(*p());
}
关于c++ - 指针传递和引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8571078/