多参数重载函数 [英] Multiple argument overloaded functions

查看:62
本文介绍了多参数重载函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一个事实,在方法重载中,优先级如下:

I have read the fact that in method overloading , Priority goes as:

精确匹配>加宽>装箱/拆箱>可变参数

这对于只有一个参数的函数非常有用.但是对于具有多个参数的函数,这有时会产生奇怪的结果,大概是因为我无法正确应用此规则.

This works great for functions having only one argument. But for functions having more than one argument this sometimes give strange results, presumably because I am not able to apply this rule correctly.

例如:

代码 1:

public static void overloadResolve(long i,int j){}      //1
public static void overloadResolve(int i,Integer o){}   //2
overloadResolve(5,6);                                   // calls 1

代码 2:

public static void overloadResolve(int i,int... j){}    //1
public static void overloadResolve(Integer i,long o){}  //2 
overloadResolve(5,6);                                   // calls 2 

你能解释一下在重载的​​情况下如何处理多参数函数吗?

Can you explain how to deal with multiple argument functions in the case of overloading?

推荐答案

嗯,在第一种情况下,第一种方法有一个需要加宽的参数和另一个完全匹配的参数.第二种方法有一个完全匹配的参数和另一个需要装箱的参数.由于加宽优先于装箱,所以选择第一种方法.

Well, in the first case, the first method has one parameter that requires widening and another that is exact match. The second method has one parameter with exact match and another that requires boxing. Since widening has precedence over boxing, the first method is chosen.

在第二种情况下,第一种方法有可变参数,而第二种方法需要装箱和加宽.由于加宽和装箱都优先于可变参数,因此选择第二种方法.

In the second case the first method has varargs, while the second requires boxing and widening. Since both widening and boxing have precedence over varargs, the second method is chosen.

你可以想出一些例子来说明选择哪种方法:

You could come up with examples where it wouldn't be clear which method to choose :

public static void overloadResolve(long i,Integer j){} //1
public static void overloadResolve(Integer i,long o){} //2
overloadResolve(5,6);

在这种情况下,第一个方法优先于第一个参数,而第二个方法优先于第二个参数.因此编译器无法在它们之间进行选择,编译就会失败.

In this case the first method has precedence for the first argument, while the second method has precedence for the second argument. Therefore the compiler can't choose between them, and compilation would fail.

这篇关于多参数重载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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