本文介绍了如果文档中另有说明,则c ++引用似乎已重新分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据问题,您不能更改引用所指的内容至.同样,C ++ Primer 5th Edition指出

According to this question you can't change what a reference refers to. Likewise the C++ Primer 5th Edition states

但是,以下代码编译并显示值4,该值看起来像我的参考被改变了??请详细说明是否这样.

However the following code compiles and prints the value 4 which looks to me like the reference was changed?? Please elaborate if this is or is not so.

int a = 2;
int b = 4;
int &ref = a;
ref = b;
cout << ref;

推荐答案

您没有重新分配参考.引用充当变量的别名.在这种情况下, ref a 的别名,因此

You are not reassigning a reference. A reference acts as an alias for a variable. In this case, ref is an alias for a, so

ref = b;

等同于

a = b;

您可以通过打印出 a 的值来轻松检查:

You can easily check that by printing out the value of a:

std::cout << a << std::endl; // prints 4

这篇关于如果文档中另有说明,则c ++引用似乎已重新分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 16:14