通过指针&通过引用传递

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)