为什么它是非法/不道德的重置一个参考? [英] Why is it illegal/immoral to reseat a reference?
问题描述
可能重复:
为什么引用在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);
}
我看到一个错误,它详细说明,他们不能重新安排,但不解释为什么。为什么?
I got an error, and looked on the faq lite. It details that they cannot be reseated, but does not explain why. Why?
推荐答案
因为有没有语法来做:
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.
这篇关于为什么它是非法/不道德的重置一个参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!