[英]Java implicit cast in function parameters
Is it possible to automatically cast an integer to an object when passing it as function parameter? 将整数作为函数参数传递时,是否可以将整数自动转换为对象? i have this function prototype: 我有这个功能的原型:
public void aggiungiA(Nodo x)
Nodo has his own constructor with an integer parameter. Nodo拥有自己的带有整数参数的构造函数。 Now, What i want do is: 现在,我想做的是:
aggiungiA(5);
with an implicit cast. 使用隐式转换。 is there anyway to do it? 反正有做吗?
There are no implicit casts via constructor invocations in java. 在Java中,没有通过构造函数调用进行隐式强制转换。 You'll have to explicitly call the constructor - either from the caller, or by overloading the method: 您必须显式地调用构造函数-从调用者或通过重载方法:
public class MyClass {
public void aggiungiA(int i) {
aggiungiA(new Nodo(i));
}
public void aggiungiA(Nodo x) {
// Do something with X
}
}
In addition to @Mureinik's answer, I guess you are coming from a C++ background where certain casts do happen automatically. 除了@Mureinik的答案以外,我猜您还来自C ++背景,某些强制转换确实会自动发生。 In Java things are different - the only implisit casts are: 在Java中,情况有所不同-唯一的隐式强制转换为:
long x = myLong + inInt
myInt will be cast to a long before the addition of the two long values 例如,在long x = myLong + inInt
将long x = myLong + inInt
转换为两个long值相加之前的long
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.