为什么在java中不允许分配给'this'?

编程入门 行业动态 更新时间:2024-10-11 19:23:06
本文介绍了为什么在java中不允许分配给'this'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我从编译器得到的错误是赋值的左侧必须是一个变量".我的用例是深度复制,但并不真正相关.

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

是的,但是您不能在 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 设为变量的决定背后的基本原理是什么.

[...] what rationale is there behind the decision not to make this a variable.

我会说清晰度/可读性.

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'?

本文发布于:2023-11-09 04:13:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571373.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中不   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!