为什么 Java 不提供运算符重载? [英] Why doesn't Java offer operator overloading?

查看:27
本文介绍了为什么 Java 不提供运算符重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 C++ 到 Java,明显没有答案的问题是为什么 Java 不包括运算符重载?

Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading?

不是复杂的a, b, c;a = b + c; 复杂的 a, b, c; 简单得多a = b.add(c);?

是否有一个已知的原因,不允许运算符重载的有效参数?原因是随意的,还是时间错了?

Is there a known reason for this, valid arguments for not allowing operator overloading? Is the reason arbitrary, or lost to time?

推荐答案

假设您想覆盖由 a 引用的对象的先前值,则必须调用成员函数.

Assuming you wanted to overwrite the previous value of the object referred to by a, then a member function would have to be invoked.

Complex a, b, c;
// ...
a = b.add(c);

在 C++ 中,此表达式告诉编译器在堆栈上创建三 (3) 个对象,执行加法,并将结果值从临时对象复制到现有对象a.

In C++, this expression tells the compiler to create three (3) objects on the stack, perform addition, and copy the resultant value from the temporary object into the existing object a.

但是,在Java中,operator=不会对引用类型进行值复制,用户只能创建新的引用类型,不能创建值类型.因此,对于名为 Complex 的用户定义类型,赋值意味着复制对现有值的引用.

However, in Java, operator= doesn't perform value copy for reference types, and users can only create new reference types, not value types. So for a user-defined type named Complex, assignment means to copy a reference to an existing value.

考虑:

b.set(1, 0); // initialize to real number '1'
a = b; 
b.set(2, 0);
assert( !a.equals(b) ); // this assertion will fail

在 C++ 中,这会复制值,因此比较将导致不相等.在 Java 中,operator= 执行引用复制,因此 ab 现在引用相同的值.结果,比较将产生相等",因为对象将与自身相等.

In C++, this copies the value, so the comparison will result not-equal. In Java, operator= performs reference copy, so a and b are now referring to the same value. As a result, the comparison will produce 'equal', since the object will compare equal to itself.

副本和引用之间的区别只会增加运算符重载的混乱.正如@Sebastian 提到的,Java 和 C# 都必须分别处理值和引用的相等性——operator+ 可能会处理值和对象,但 operator= 已经实现为处理引用.

The difference between copies and references only adds to the confusion of operator overloading. As @Sebastian mentioned, Java and C# both have to deal with value and reference equality separately -- operator+ would likely deal with values and objects, but operator= is already implemented to deal with references.

在 C++ 中,您应该一次只处理一种比较,这样可以减少混淆.例如,在 Complex 上,operator=operator== 都在处理值——分别复制值和比较值.

In C++, you should only be dealing with one kind of comparison at a time, so it can be less confusing. For example, on Complex, operator= and operator== are both working on values -- copying values and comparing values respectively.

这篇关于为什么 Java 不提供运算符重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆