繁体   English   中英

为什么不能将cout与用户定义的转换一起使用到std :: string?

[英]Why cannot use cout with user-defined conversion to std::string?

在这里,我定义一个Date ,并指定一个用户定义的转换。

class Date {
private:
    int day;
    int month;
    string dateStr;
public:
    Date(int _day, int _month) : day(_day), month(_month) {}

    operator const string() {
        ostringstream formattedDate;
        formattedDate << month << "/" << day;
        dateStr = formattedDate.str();
        return dateStr;
    }
};

转换为string时效果很好。

Date d(1, 1);
string s = d;

但是为什么不能直接与cout一起使用呢?

cout << d << endl; // The compiler complains that there is no suitable type marching << operator

但是,如果我使用char*而不是string进行用户定义的转换,则可以直接将其与cout一起使用。 为什么?

operator const char*() { 
    ostringstream formattedDate;
    formattedDate << month << " / " << day;
    dateStr = formattedDate.str();
    return dateStr.c_str();
}

PS。 我知道直接<<重载将很好地用于输出。 但是我的问题是: 为什么不能将<<和用户定义的转换一起使用到std::string

需要注意的是std::string是模板实例化std::basic_string签名operator<<std::string确实是:

template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>& 
    operator<<(std::basic_ostream<CharT, Traits>& os, 
               const std::basic_string<CharT, Traits, Allocator>& str);

然后为cout << d; ,必须推导std::basic_string的模板参数; 但是类型推导不考虑隐式转换 ;

类型推导不考虑隐式转换(上面列出的类型调整除外):这是超载解析的工作,稍后会发生。

这意味着扣除将失败; 那么没有候选函数是可行的。

但是operator<< for const char*并没有这种问题; 隐式转换生效,然后正常工作。

要解决此问题,可以使用显式转换来避免模板参数的推导。 或直接在Date类型上重载operator<<

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM