C ++ conversion operators no candidate better

    #include <iostream>
#include <string>

using namespace std;

class test {
    private:
        std::string strValue;
        int value;

    public:
        test():value(0) { };
        test(int a):value(a) { };
        test(std::string a):strValue(a) { };
        ~test(){};

        operator int () { return value; }
        operator const char* () { return strValue.c_str(); }
};

int main() {
    test v1(100);
    cout << v1  << endl;
    return 0;
}

When I run the above, with gcc I get an error when none of the candidates is suitable for conversion. Are they exceptional types?

+3
source share
2 answers

std::ostreamIt has many overloads operator<<, including both of the following:

std::ostream& operator<<(std::ostream&, const char*);
std::ostream& operator<<(std::ostream&, int);

Your class testcan be converted both to const char*and to int. The compiler cannot choose which transform to use, since both transforms will work equally well. Thus, the conversion is ambiguous.

+5
source

test v1 (100); cout <v1 <cps;

cout < < (ostream &, test) . , ostream, .

0

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


All Articles