3

我不明白这里发生了什么

class A{};
class B : A {};

void func(A&, bool){}
void func(B&, double){}

int main(void)
{
    B b;
    A a;
    bool bo;
    double d;

    func(b, bo);
}

编译时,Visual 2010 在线给我这个错误func(b, bo);

2 overloads have similar conversions
could be 'void func(B &,double)'
or       'void func(A &,bool)'
while trying to match the argument list '(B, bool)'

我不明白为什么 bool 参数不足以解决过载问题。我已经看到了这个问题,并且正如接受的答案所指出的那样, bool 应该更喜欢 bool 重载。就我而言,我看到第一个参数不足以选择好的功能,但为什么第二个参数不能解决歧义?

4

2 回答 2

5

重载规则比你想象的要复杂一些。您分别查看每个参数并为该参数选择最佳匹配。然后,如果恰好有一个重载为每个参数提供了最佳匹配,那就是被调用的那个。在示例中,第一个参数的最佳匹配是 的第二个版本func,因为它只需要转换BB&; 另一个版本func需要先转换B为. 对于第二个参数,第一个版本B&B&A&func是最佳匹配,因为它不需要转换。第一个版本有第二个参数的最佳匹配,但它没有第一个参数的最佳匹配,所以不考虑它。同样,第二个版本对第一个参数有最佳匹配,但对第二个参数没有最佳匹配,因此不考虑。现在没有funcleft 的版本,调用失败。

于 2012-08-23T15:42:05.687 回答
2

Overload resolution rules are even more complicated than Pete Becker wrote. For each overload of f, the compiler counts not only the number of parameters for which conversion is required, but the rank of conversion.

Rank 1

No conversions required

Lvalue-to-rvalue conversion

Array-to-pointer conversion

Function-to-pointer conversion

Qualification conversion

Rank 2

Integral promotions

Floating point promotions

Rank 3

Integral conversions

Floating point conversions

Floating-integral conversions

Pointer conversions

Pointer to member conversions

Boolean conversions

Assuming that all candidates are non-template functions, a function wins if and only if it has a parameter which rank is better than the rank of the same parameter in other candidates and the ranks for the other parameters are not worse.

Now let's have a look at the OP case.

  • func(A&, bool): conversion B&->A& (rank 3) for the 1st parameter, exact match (rank 1) for the 2nd parameter.
  • func(B&, double): exact match (rank 1) for the 1st parameter, conversion bool->double (rank 3) for the 2nd parameter.

Conclusion: noone wins.

于 2012-08-23T15:54:46.627 回答