通过指针&通过引用 [英] Pass by pointer & Pass by reference

查看:182
本文介绍了通过指针&通过引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:



在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\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& < => [无C等价] (C ++ 11)

与其他答案一样,C ++ FAQ中的以下是单行答案

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());
}

这篇关于通过指针&amp;通过引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆