重新分配C++引用变量

Reassigning C++ reference variables

本文关键字:C++ 引用 变量 分配 新分配      更新时间:2023-10-16

我试图理解C++引用变量。此链接似乎表明可以在初始化时重新分配指针,同时应分配引用。指针和引用之间的区别。我在下面有以下代码。我已经在 debian 系统上运行了它。输出也如下所示。输出似乎表明也可以重新分配引用。如果有人能澄清,那就太好了。

#include <iostream>
using namespace std;
int main()
{
  int x = 5;
  int y = 6;
  int *p; 
  p = &x; 
  cout << "content of p " << *p << endl;
  p = &y; 
  cout << "content of p " << *p << endl;
  *p = 10; 
  cout << "content of p " << *p << endl;
  /*A reference must be assigned at initialization*/
  int &r = x;
  cout << "content of r " << r << endl;
  r = y;
  cout << "content of r " << r << endl;

  return 0;
}

输出

content of p 5
content of p 6
content of p 10
content of r 5
content of r 10

您在这里看到的是分配给引用变量引用的变量的值。

换句话说:
您没有为引用变量分配新值。您为引用的变量分配了新值。