[英]Overload resolution and user-defined conversion
Consider this example:考虑这个例子:
struct Foo
{
Foo(int){cout << "Foo(int)\n";}
Foo(double){cout << "Foo(double)\n";}
operator int()const{cout << "operator int()\n"; return 0;}
operator double()const{cout << "operator double()\n"; return 0.;}
};
void bar(Foo){cout << "bar(Foo)\n";}
void bar(float){cout << "bar(float)\n";}
int main()
{
int i = 5;
bar(i); // whey bar(float) and not bar(Foo)?
}
I know I shouldn't overload the "converting-ctor" to take relate types (here arithmetic types) but just for understanding better function matching and user-defined-conversion.我知道我不应该重载“converting-ctor”来获取相关类型(这里是算术类型),而只是为了更好地理解 function 匹配和用户定义的转换。
Why the call to bar is resolved to bar(float)
and not bar(Foo)
as long as Foo
has an exact match for this argument ( int
)?为什么只要Foo
与此参数( int
)完全匹配,对 bar 的调用就会解析为bar(float)
而不是bar(Foo)
) ?
Does it mean that standard conversion is preferred over user-defined conversion?这是否意味着标准转换优于用户定义的转换?
Does it mean that standard conversion is preferred over user-defined conversion?这是否意味着标准转换优于用户定义的转换?
Yes.是的。 Standard conversions are always preferred over user-defined ones.标准转换总是优先于用户定义的转换。 See this看到这个
In deciding on the best match, the compiler works on a rating system for the way the types passed in the call and the competing parameter lists match up.在决定最佳匹配时,编译器使用评级系统来确定调用中传递的类型和竞争参数列表匹配的方式。 In decreasing order of goodness of match:按照匹配度的降序排列:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.