Overloading << operator for std::ostream

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


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 11:49

    Your storage report implicitely is always streamed to cout. Imagine someone calling your function this way and having the rentals on cout instead of the file.

    fstream fs("out.txt");
    storageRentals rentals;
    fs << rentals;
    

    Why don't you stream your class like this:

    ostream& operator <<(ostream& osObject, const storageRentals& rentals)
    {
    
      for (int count = 0; count < 8; count++) {
          osObject << "Unit: " << count + 1 << "    " << rentals.stoUnits[count] << endl;
      }
      return osObject;
    }
    

    If the stoUnits member is private you need to make the stream function a friend of your storage class.

    friend ostream& operator<<(ostream& osObject, const storageRentals& rentals);
    

提交回复
热议问题