重新分配C ++参考变量 [英] Reassigning C++ reference variables

查看:116
本文介绍了重新分配C ++参考变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解C ++参考变量.该链接似乎表明可以在初始化时重新分配一个指针,同时应分配一个引用. 指针与引用之间的差异.我下面有以下代码.我已经在Debian系统上运行了它.输出也如下所示.输出似乎表明也可以重新分配引用.如果有人可以澄清,那就太好了.

I am trying to understand C++ reference variables. This link seems to indicate that a pointer can be reassigned while a reference should be assigned at initialization. difference between pointer and reference. I have the following code below. I have run it on a debian system. The output is also shown below. The output seems to indicate that reference can be reassigned as well.It would be great if someone could clarify.

#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

推荐答案

在这里看到的是将值分配给引用变量所引用的变量.

What you see here is the value being assigned to the variable referenced by the referencing variable.

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

In other words:
You did not assign new value to the referencing variable. You assigned a new value to the referenced variable.

这篇关于重新分配C ++参考变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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