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

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

问题描述

从C ++到Java,明显的未解决的问题是为什么没有Java包含运算符重载?

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

不是 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)

表达式告诉编译器在堆栈上创建3个对象,执行添加,并将临时对象的结果值复制到现有对象'a'中。

In C++, this expression tells the compiler to create 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) );

在C ++中,这会复制该值,因此比较结果将不等于。在Java中,operator =执行引用副本,因此a和b现在指的是相同的值。因此,比较将产生等于,因为对象将比较等于它自己。

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天全站免登陆