gpt4 book ai didi

java - C++ 与 Java 中函数重载的歧义

转载 作者:行者123 更新时间:2023-11-28 00:03:46 26 4
gpt4 key购买 nike

在 C++ 中的函数重载的情况下,我们知道在实际和形式参数不匹配方面可能会出现歧义。所以有一个机制来解决这个问题。

For every actual parameter P, Si be the set of corresponding formal parameters that matches best. then S will be the intersection of all Si.

为此,有 4 种类型的规则。

  1. 完全匹配
  2. 晋升
  3. 标准转化
  4. 用户定义的转化
  5. 省略号(所有人都不考虑)

类似的过程是否也发生在 Java 中?由于函数重载规则在 Java 中是相同的,所以这里也可能发生歧义。

最佳答案

类似的过程?好吧,这取决于“相似”的含义。

然而,它在 Java 语言规范中有详细记录,
15.12 Method Invocation Expressions
尤其是子章15.12.2. Compile-Time Step 2: Determine Method Signature .

The process of determining applicability begins by determining the potentially applicable methods (§15.12.2.1).

The remainder of the process is split into three phases, to ensure compatibility with versions of the Java programming language prior to Java SE 5.0. The phases are:

  1. The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

  2. The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.

  3. The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.

Deciding whether a method is applicable will, in the case of generic methods (§8.4.4), require an analysis of the type arguments. Type arguments may be passed explicitly or implicitly. If they are passed implicitly, bounds of the type arguments must be inferred (§18 (Type Inference)) from the argument expressions.

If several applicable methods have been identified during one of the three phases of applicability testing, then the most specific one is chosen, as specified in section §15.12.2.5.

章节15.12.2.5 Choosing the Most Specific Method总结得很好:

The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

当然,比这要复杂一些。

关于java - C++ 与 Java 中函数重载的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com