c ++转换运算符没有候选者更好

Kir*_*ran 3 c++ operator-overloading operators

    #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;
}
Run Code Online (Sandbox Code Playgroud)

当我运行上面的内容时,使用gcc我得到一个错误,说没有候选人更适合转换..这不是他们的独家类型吗?

Jam*_*lis 5

std::ostream有许多operator<<重载,包括以下两个:

std::ostream& operator<<(std::ostream&, const char*);
std::ostream& operator<<(std::ostream&, int);
Run Code Online (Sandbox Code Playgroud)

你的test班级可以转换为const char*int.编译器无法选择要使用的转换,因为两个转换都可以同样正常工作.因此,转换是模糊的.

  • 是的,您可以使用强制转换,但更好的解决方案是不使用转换运算符. (4认同)