问题描述
可能的重复:
为什么引用不能在 C++ 中重新安装
我正在尝试或多或少地交换两个参考变量(作为实践,我本可以交换实际变量).我尝试通过创建一个临时变量并使一个引用与另一个引用相等来做到这一点,但这被编译器拒绝了.下面是一个例子:
I am trying to more or less swap two reference variables (as practice, I could have swapped the actual variables). I tried doing this by making a temporary variable and making one of the references equal the other, but this got shot down by the compiler. Here is an example:
void Foo()
{
//code
int& ref1 = a;
int& ref2 = b;
int temp;
temp = ref1;
ref1 = ref2;
ref2 = temp;
//or, better yet
std::swap(ref1, ref2);
}
我遇到了一个错误,并查看了 faq lite.它详细说明它们不能重新安装,但没有解释原因.为什么?
I got an error, and looked on the faq lite. It details that they cannot be reseated, but does not explain why. Why?
这里是 Faq Lite 的链接以供参考 (<;---,明白了吗?)
Here is a link to the Faq Lite for reference (<---, get it?).
推荐答案
因为没有语法可以做到:
Because there is no syntax to do it:
int x = 0;
int y = 1;
int & r = x;
现在如果我说:
r = y;
我将 y 的值赋给 x.如果我想重新安装,我需要一些特殊的语法:
I assign the value of y to x. If I wanted to reseat I would need some special syntax:
r @= y; // maybe?
由于使用引用的主要原因是作为函数的参数和返回类型,在这不是问题的情况下,C++ 的设计者似乎并不认为这是一条值得走的路.
As the main reason for using references is as parameters and return types of functions, where this is not an issue, it didn't seem to C++'s designers that this was a path worth going down.
这篇关于为什么重新设置参考是非法/不道德的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!