C ++:operator<<隐式转换优先级

时间:2014-09-17 13:22:13

标签: c++ casting operator-overloading

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

class R {
public:
    R(double x) : _x(x) {}
    operator string () {cout << "In string operator\n"; return std::to_string(_x);}
    operator double () {cout << "In double operator\n"; return _x;}
private:
    double _x;
};

int main() {
    R r(2.5);
    cout << r << endl;
    return 0;
}

1 个答案:

答案 0 :(得分:0)

这是因为operator std::string()根本不可行。 operator<<过载basic_string

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 doublewatching your code explode来查看此内容。