function overload and type conversion resolution

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

why do we not see a "undefined call to overloaded function" error with the code bellow? just because int is a built in type? where in the standard can I find the guarantee for the conversion to built in type, such as in the code bellow?... thanks!

#include <iostream> using namespace std;  class B { public: operator int(){ return 0; } };  class A { public: A( int i ) { }; };  void f ( int i ) { cout << "overload f(int) was used!";}; void f ( A a )   { cout << "overload f(A) was used!" ;};   int main () {   B b;   f( b ); } 

回答1:

It has nothing to do with being a built-in type. You defined operator int for B. This means that you have provided a user-defined conversion from B to int. According to 12.3.4 of the standard, "at most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value." This is why it is not converted to A, because that would require two implicit conversions.

The rules for determining exactly when this happens are somewhat complicated, so many people advise that you avoid providing user-defined conversions. Another way of defining these is to provide a constructor with one argument; you can add explicit to the beginning to avoid it being applied implicitly.

When you call f(b), the compiler applies the conversion that you provided to convert b to int. If you want to convert it to A, you'll have to define a conversion from B to A, or apply one of the conversions explicitly, like f(int(b)) or f(A(b)).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!