Conversion operator + conversion constructor = unintuitive behavior?

前端 未结 2 733
花落未央
花落未央 2021-01-04 12:54

I don\'t understand why the code below prints struct Value instead of int (which implies the conversion constructor is converting to Value

2条回答
  •  悲哀的现实
    2021-01-04 13:24

    I've tried your code (on the Visual Studio version only).

    Since you have a built-in copy-CTOR, I guess your main is equal to:

    int main()
    {
        try { Value w((struct Value)(Convertible())); }
        catch (char const *s) { cerr << s << endl; }
    }
    

    The compiler has chosen to use your copy CTOR, rather than Value(int).

    Changing it to:

    int main()
    {
        try { Value w((int)(Convertible())); }
        catch (char const *s) { cerr << s << endl; }
    }
    

    It printed "int".

提交回复
热议问题