这里我定义一个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;
}
};
Run Code Online (Sandbox Code Playgroud)
转换为时效果很好string.
Date d(1, 1);
string s = d;
Run Code Online (Sandbox Code Playgroud)
但为什么不能cout直接使用呢?
cout << d << endl; // The compiler complains that there is no suitable type marching << operator
Run Code Online (Sandbox Code Playgroud)
但是,如果我使用char*而不是string用户定义的转换,我可以cout直接使用它.为什么? …
c++ cout operator-overloading type-conversion implicit-conversion