Here I define a Date, and specify a user-defined conversion.
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;
}
};
It works well when converting to string.
Date d(1, 1);
string s = d;
But why cannot use it with cout directly?
cout << d << endl; // The compiler complains that there is no suitable type marching << operator
However, if I use char* instead of string for user-defined conversion, I can use it with cout directly. Why?
operator const char*() {
ostringstream formattedDate;
formattedDate << month << " / " << day;
dateStr = formattedDate.str();
return dateStr.c_str();
}
ps. I know that overloading << directly will work well for output. But my question is: why cannot use << with user-defined conversion to std::string?
operator<<function instead of relying on conversion operators. (And if you still want to have a conversion operator, you can use the overloaded<<operator to create it.)