Why does an implicit conversion operator double the value that exceeds the conversion to std :: string?

If I define several conversion operators for my class:

#include <iostream>
#include <string>

class Widget {
public:
    operator double() {
        return 42.1;
    }

    operator std::string() {
        return "string";
    }
};

int main(void) {
    Widget w;
    std::cout << w << std::endl;

    return 0;
}

the output of this value is equal 42.1even if I reorder the member functions.

Why does the compiler always use operator double()instead operator std::string()? What are the rules for resolving a function for this?

If I define a second conversion operator on intinstead std::string, the compiler will complain about the ambiguous call.

+4
source share

No one has answered this question yet.

Source: https://habr.com/ru/post/1677644/


All Articles