Can someone tell me what is wrong when I try to overload <<
in a slightly different way by using another symbol like <<=
#include <iostream>
struct Date {
int day, month, year, hour, minute, second;
Date (int d, int m, int y, int h, int min, int s) { day = d; month = m; year = y; hour = h; minute = min; second = s; }
friend std::ostream& operator << (std::ostream&, const Date&);
friend std::ostream& operator <<= (std::ostream&, const Date&); // Carries out << but without the hour, minute, and second.
};
std::ostream& operator << (std::ostream& os, const Date& d) {
os << d.day << ' ' << d.month << ' ' << d.year << ' ' << d.hour << ' ' << d.minute << ' ' << d.second;
return os;
}
std::ostream& operator <<= (std::ostream& os, const Date& d) {
os << d.day << ' ' << d.month << ' ' << d.year;
return os;
}
int main () {
Date date(25, 12, 2021, 8, 30, 45);
std::cout << "Today is " << date << '\n'; // Works fine
std::cout << "Today is " <<= date << '\n'; // Does not work
}
If I use
std::cout << "Today is " <<= date;
It works fine, so what is the problem with adding in << '\n'
when std::ostream& is returned by <<=
?
CodePudding user response:
Due to the operator precedence this statement
std::cout << "Today is " <<= date << '\n';
is equivalent to
( std::cout << "Today is " ) <<= ( date << '\n' );
and the right most expression
( date << '\n' )
produces an error because such an operator is not defined for objects of the type struct Date
.
CodePudding user response:
Thanks to Vlad from Moscow's answer,
(std::cout << "Today is " <<= date) << '\n';
is the simple fix. Not as pretty as was desired, but works correctly.
Perhaps defining a derived class DateAndTime
of Date
that has the hours, minutes, and seconds and then overloading << for DateAndTime
may be a more elegant, but longer, solution.