C++:运算符<<隐式强制转换优先级

C++: operator << implicit cast priority

本文关键字:lt 转换 优先级 C++ 运算符      更新时间:2023-10-16

在下一个例子中,为什么operator <<更喜欢转换为double而不是字符串?是因为原语具有更高的优先级吗?

class R {
public:
    R(double x) : _x(x) {}
    operator string () {cout << "In string operatorn"; return std::to_string(_x);}
    operator double () {cout << "In double operatorn"; return _x;}
private:
    double _x;
};
int main() {
    R r(2.5);
    cout << r << endl;
    return 0;
}
这是因为operator std::string()根本不可行。占用basic_string s的operator<<过载为
template<class charT, class traits, class Allocator>
basic_ostream<charT, traits>&
operator<<(basic_ostream<charT, traits>& os, const basic_string<charT,traits,Allocator>& str);

模板参数推导不能从类型R中推导出模板参数。它不会查看隐式转换。

您可以通过注释operator double并观察代码爆炸来看到这一点。