Overloading << operator for std::ostream

后端 未结 4 1544
灰色年华
灰色年华 2021-01-14 11:07
ostream& operator <<(ostream& osObject, const storageRentals& rentals)
{
    osObject << rentals.summaryReport();
    return osObject;
}
         


        
4条回答
  •  天命终不由人
    2021-01-14 11:48

    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.

提交回复
热议问题