1

i am trying to overload operator<< to write my Class in a file but insert more lines at the same time ( more objects ).

friend void operator<<(ofstream& o,Departament&d)
{
    o<<d.denumire<< " " << d.nrAngajati << " ";
    for(int i = 0 ; i< d.nrAngajati-1; i++)
    {
        o<<d.efortOmOre[i]<<", ";
    }
    o<<d.efortOmOre[d.nrAngajati-1]<<"."<<endl;
}

And i can write in file with it but with just one object at the time. Something like this.

Class a,b,c;
fisOut("out.txt");
fisOut<< a; fisOut<<b; fisOut<<c;
fisOut.close();

but what i really need to do its this:

fisOut<<a<<b<<c;
fisOut.close();

How can i do that?

ZZR
  • 21
  • 1

1 Answers1

3

It is best practice to make the << operator return the stream itself. This allows to chain outputs like you desire.

So:

friend ofstream& operator<<(ofstream& o,Departament&d)
{
    ...
    return o;
}
Rémi Bonnet
  • 793
  • 5
  • 16