问题描述
我从编译器得到的错误是赋值的左侧必须是一个变量".我的用例是深度复制,但并不真正相关.
The error I get from the compiler is "The left hand side of an assignment must be a variable". My use case is deep copying, but is not really relevant.
在C++中,可以赋值给*this
.
In C++, one can assign to *this
.
问题不是如何绕过对this
的赋值.这很简单,而是决定不将 this
设为变量的原因是什么.
The question is not how to circumvent assignment to this
. It's very simple, but rather what rationale is there behind the decision not to make this
a variable.
原因是技术上的还是概念上的?
Are the reasons technical or conceptual?
到目前为止我的猜测 - 以随机方法重建对象的可能性容易出错(概念上),但在技术上是可行的.
My guess so far - the possibility of rebuilding an Object in a random method is error-prone (conceptual), but technically possible.
EDIT 请限制因为 Java 规范这么说"的变体.我想知道决定的原因
EDIT Please restrain from variations of "because java specs say so". I would like to know the reason for the decision
推荐答案
是的,但是您不能在 C++ 中执行 this = something
,我实际上认为这与您在 Java 方面所询问的内容更接近.
Yes, but you can't do this = something
in C++, which I actually believe is a closer match for what you're asking about on the Java side here.
[...] 不将 this
设为变量的决定背后的基本原理是什么.
我会说清晰度/可读性.
I would say clarity / readability.
this
被选为保留字,可能是因为它没有作为显式参数传递给方法.将其用作普通参数并能够为其重新分配新值,会严重影响可读性.
this
was chosen to be a reserved word, probably since it's not passed as an explicit argument to a method. Using it as an ordinary parameter and being able to reassign a new value to it, would mess up readability severely.
事实上,出于这个原因,很多人认为根本不应该更改参数变量.
In fact, many people argue that you shouldn't change argument-variables at all, for this very reason.
原因是技术上的还是概念上的?
我认为主要是概念性的.不过会出现一些技术怪癖.如果您可以为 this
重新分配一个值,则您可以将实例变量完全隐藏在局部变量后面.
Mostly conceptual I would presume. A few technical quirks would arise though. If you could reassign a value to this
, you could completely hide instance variables behind local variables for example.
到目前为止我的猜测 - 以随机方法重建对象的可能性容易出错(概念上),但在技术上是可行的.
我不确定我是否完全理解这句话,但是是的,容易出错可能是决定将其作为关键字而不是变量的主要原因.
I'm not sure I understand this statement fully, but yes, error prone is probably the primary reason behind the decision to make it a keyword and not a variable.
这篇关于为什么在java中不允许分配给'this'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!