指针变量和引用变量之间的区别是什么?


当前回答

这是基于教程。所写内容更清楚:

>>> The address that locates a variable within memory is
    what we call a reference to that variable. (5th paragraph at page 63)

>>> The variable that stores the reference to another
    variable is what we call a pointer. (3rd paragraph at page 64)

简单地记住,

>>> reference stands for memory location
>>> pointer is a reference container (Maybe because we will use it for
several times, it is better to remember that reference.)

此外,我们可以参考几乎任何指针教程,指针是指针算术支持的对象,它使指针类似于数组。

看看下面的陈述,

int Tom(0);
int & alias_Tom = Tom;

alias_Tom可以理解为变量的别名(与typedef不同,typedef是一种类型的别名)Tom。忘记这种说法的术语也是可以的,即创建一个对汤姆的引用。

其他回答

你忘记了最重要的部分:

带指针的成员访问使用->使用引用的成员访问。

foo.bar明显优于foo->bar,就像vi明显优于Emacs一样:-)

引用是另一个变量的别名,而指针保存变量的内存地址。引用通常用作函数参数,因此传递的对象不是副本而是对象本身。

    void fun(int &a, int &b); // A common usage of references.
    int a = 0;
    int &b = a; // b is an alias for a. Not so common to use. 

在C++中,对指针的引用是可能的,但反之则不可能,这意味着指向引用的指针是不可能的。对指针的引用提供了一种更简洁的语法来修改指针。看看这个例子:

#include<iostream>
using namespace std;

void swap(char * &str1, char * &str2)
{
  char *temp = str1;
  str1 = str2;
  str2 = temp;
}

int main()
{
  char *str1 = "Hi";
  char *str2 = "Hello";
  swap(str1, str2);
  cout<<"str1 is "<<str1<<endl;
  cout<<"str2 is "<<str2<<endl;
  return 0;
}

并考虑上述程序的C版本。在C语言中,你必须使用指针对指针(多重间接寻址),这会导致混乱,程序可能看起来很复杂。

#include<stdio.h>
/* Swaps strings by swapping pointers */
void swap1(char **str1_ptr, char **str2_ptr)
{
  char *temp = *str1_ptr;
  *str1_ptr = *str2_ptr;
  *str2_ptr = temp;
}

int main()
{
  char *str1 = "Hi";
  char *str2 = "Hello";
  swap1(&str1, &str2);
  printf("str1 is %s, str2 is %s", str1, str2);
  return 0;
}

有关指针引用的详细信息,请访问以下内容:

C++:指针引用指向指针的指针和指向指针的引用

正如我所说,指向引用的指针是不可能的。尝试以下程序:

#include <iostream>
using namespace std;

int main()
{
   int x = 10;
   int *ptr = &x;
   int &*ptr1 = ptr;
}

这个程序可能有助于理解问题的答案。这是一个引用“j”和指向变量“x”的指针“ptr”的简单程序。

#include<iostream>

using namespace std;

int main()
{
int *ptr=0, x=9; // pointer and variable declaration
ptr=&x; // pointer to variable "x"
int & j=x; // reference declaration; reference to variable "x"

cout << "x=" << x << endl;

cout << "&x=" << &x << endl;

cout << "j=" << j << endl;

cout << "&j=" << &j << endl;

cout << "*ptr=" << *ptr << endl;

cout << "ptr=" << ptr << endl;

cout << "&ptr=" << &ptr << endl;
    getch();
}

运行程序并查看输出,您就会明白。

另外,抽出10分钟观看以下视频:https://www.youtube.com/watch?v=rlJrrGV0iOg

以下答案和链接的摘要:

指针可以被重新分配任意次数,而引用在绑定后不能被重新分配。指针可以指向任何地方(NULL),而引用总是指向对象。不能像使用指针那样获取引用的地址。没有“引用算术”(但您可以获取引用指向的对象的地址,并对其进行指针算术,如&obj+5中所示)。

澄清误解:

C++标准非常小心,避免规定编译器如何实现引用,但每个C++编译器都实现引用作为指针。即,声明如下:int&ri=i;如果没有完全优化,则分配相同数量的存储作为指针,并放置地址把我的东西放进那个储藏室。

因此,指针和引用都使用相同的内存量。

作为一般规则,

使用函数参数和返回类型中的引用来提供有用的自记录接口。使用指针实现算法和数据结构。

有趣的阅读:

我最喜欢的C++常见问题解答。参考与指针。参考文献简介。参考和常量。