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 <<= ?
Due to the operator precedence this statement
is equivalent to
and the right most expression
produces an error because such an operator is not defined for objects of the type
struct Date.