通过指针&通过引用传递

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;通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)