”“x2B” Java 类的运算符
我有一个这样的类:
private static class Num {
private int val;
public Num(int val) {
this.val = val;
}
}
是否可以使用“+”运算符添加到该类的对象?
Num a = new Num(18);
Num b = new Num(26);
Num c = a + b;
I have a class like this:
private static class Num {
private int val;
public Num(int val) {
this.val = val;
}
}
Is it possible to add to objects of the class by using the "+"-operator?
Num a = new Num(18);
Num b = new Num(26);
Num c = a + b;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,你不能。
+
仅对数字、字符和String
进行重载,并且不允许您定义任何其他重载。有一种特殊情况,当您可以连接任何对象的字符串表示形式时 - 如果前两个操作数中有一个
String
对象,则在所有其他操作数上调用toString()
对象。这是一个例子:
No, you can't.
+
is overloaded only for numbers, chars andString
, and you are not allowed to define any additional overloadings.There is one special case, when you can concatenate any objects' string representation - if there is a
String
object in the first two operands,toString()
is called on all other objects.Here's an illustration:
不,因为詹姆斯·高斯林这样说:
来源:http://www.gotw.ca/publications/c_family_interview.htm
参考: 为什么 Java 不提供运算符重载?
No, because James Gosling said so:
Source: http://www.gotw.ca/publications/c_family_interview.htm
Reference: Why doesn't Java offer operator overloading?
不可以。Java 不支持运算符重载(对于用户定义的类)。
No. Java does not support operator overloading (for user-defined classes).
java中没有运算符重载。
对象唯一支持的是通过“+”进行字符串连接。如果您有一系列通过“+”连接的对象,并且其中至少一个是字符串,那么结果将内联到字符串创建。示例:
将内联到
There is no operators overloading in java.
The only thing which is supported for objects, is string concatenations via "+". If you have a sequences of objects joined via "+" and at least one of them is a String, then the result will be inlined to String creation. Example:
will be inlined to
不,这是不可能的,因为 Java 不支持运算符重载。
No, it is not possible, as Java doesn't support operator overloading.