0

My ostream friend function works correctly but my ofstream nor ifstream work correctly as the errors that are given state that the different private members cannot be accessed through the ofstream or ifstream functions. Please help.

class Module 
{ 
public: 
   Module() = default; 
   explicit Module(const string& purpose, const string& id)  
   {  
      this->purpose = purpose; 
      this->id = id; 
   } 
   explicit Module(const string& purpose) { this->purpose = purpose; } 
   ~Module() { } 

   virtual void setCrew( ) = 0; 
   virtual void display( ) = 0; 
   void addCrew(Crew c) { crew_list.push_back(c); } 
   void setPowerReq(double power) { this->power = power; }  
   void setMaxCrew(int max_crew) { this->max_crew = max_crew; } 

   string getPurpose( ) { return purpose; } 
   string getId( ) { return id; } 
   int getNumberOfCrew( ) { return number_of_crew; } 
   int getMaxCrew( ) { return max_crew; } 
   double getPower( ) { return power; }  

   friend ostream& operator << ( ostream& os, const Module& m ); 
   friend ofstream& operator << ( ofstream os, const Module& m ); 
   friend ifstream& operator >> ( ifstream is, Module& m ); 

private: 
   static string purpose; 
   string id = "unknown"; 
   int number_of_crew = 0; 
   int max_crew = 0; 
   double power = 0; 
   vector<Crew> crew_list;  
};

#include "module.h"

string Module::purpose = "Module";

ofstream& operator << ( ofstream& os, const Module& m )
{
  os << m.purpose << endl
      << m.id << endl
      << m.number_of_crew << endl
      << m.max_crew << endl
      << m.power << endl;
   for ( auto i : m.crew_list )
   {
      os << i << endl;
   }
   return os;
}

ifstream& operator >> ( ifstream& is, Module& m )
{
   getline( is, m.purpose );
   return is;
}

ostream& operator << ( ostream& os, const Module& m )
{
   os << m.purpose << endl
      << m.id << endl
      << m.number_of_crew << endl
      << m.max_crew << endl
      << m.power << endl;
   for ( auto i : m.crew_list )
   {
      os << i << endl;
   }
   return os;
}
  • 1
    Normally streaming operators only need to be overloaded for `std::ostream` and `std::istream` - overloads for `std::ofstream` and `std::ifstream` are usually unnecessary. In any event, the reason your `ofstream` and `ifstream` versions won't work is that the friend declarations specify the streams are passed by value, but your definition of those functions passes them by reference - i.e. the functions you've implemented are not friends. – Peter Oct 08 '16 at 06:17
  • 1
    Short version: `ofstream os` in your friend insertion decl should be `ofstream& os`, matching your implementation. Rinse, repeat for the extraction overload. – WhozCraig Oct 08 '16 at 06:21
  • Thanks for spotting that for me! – Alex Neumann Oct 08 '16 at 06:22

0 Answers0