Overloading << operator for std::ostream
c++, overloading
Solution
You should define `summartReport` taking `ostream&` as parameter, as shown here:
std::ostream& storageRentals::summaryReport(std::ostream & out) const
{
//use out instead of cout
for (int count = 0; count < 8; count++)
out << "Unit: " << count + 1 << " " << stoUnits[count] << endl;
return out; //return so that op<< can be just one line!
}
then call it as:
ostream& operator <<(ostream& osObject, const storageRentals& rentals)
{
return rentals.summaryReport(osObject); //just one line!
}
By the way, it is not called "overloading cout". You should say, "overloading `operator<<` for `std::ostream`.
Problem
``` ostream& operator <<(ostream& osObject, const storageRentals& rentals) { osObject << rentals.summaryReport(); return osObject; } ``` `summaryReport()` is a void function, and it is giving me an error: no operator "<<" matches these operands but the error is not there if I change the `summaryReport` function to an `int`, but the problem I have with that is you have to return a value, and it is printing it out on the screen. ``` void storageRentals::summaryReport() const { for (int count = 0; count < 8; count++) cout << "Unit: " << count + 1 << " " << stoUnits[count] << endl; } ``` Is there any way to overload `cout <<` with a void function?