开发者

c++ conversion operators no candidate is 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 saying no candidate is better for conversion.. Aren't they exclusive types?


std::ostream has numerous operator<< overloads, including both of the following:

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

Your test class is convertible to both const char* and to int. The compiler can't select which conversion to use because both conversions would work equally well. Thus, the conversion is ambiguous.


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

Since cout doesn't have operator << (ostream&, test) it tries conversions. You provided two, both types are defined with ostream, so you got ambiguity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜