当我写这样的代码时:
struct foo {
operator int() const { return 1; }
};
int main() {
foo a, b;
auto tmp = (a < b);
}
Run Code Online (Sandbox Code Playgroud)
它工作,但我写这样的代码:
struct foo {
operator string() const { return string("foo"); }
};
int main() {
foo a, b;
auto tmp = (a < b);
}
Run Code Online (Sandbox Code Playgroud)
编译器(clang ++)说 error: invalid operands to binary expression ('foo' and 'foo')
我想知道为什么,因为string类型和int类型都有比较运算符,但是当foo有用户定义的int转换时,它会隐式转换int为比较,但是当foo只有用户定义的string转换时,编译器不会进行隐式转换,但(string)a<(string)b效果很好.