Overloading << and >> in inherited classes

I have a Person class (first name, last name, address, age) and overloaded operators <<and → use it with filters:

ostream& operator<< (ostream& outStream, Person& person)
{
  ...
}

istream& operator>> (istream& inStream, Person& person)
{
  ...
}

It works great - I can easily read and write to a file, but I added two classes inherited from Person: Student and Worker.

I wrote overloaded operators for them, very similar to the ones above:

ostream& operator<< (ostream& outStream, Worker& worker)
{
 ...
}

istream& operator>> (istream& inStream, Worker& worker)
{
 ...
}


ostream& operator<< (ostream& outStream, Student& student)
{
 ...
}

istream& operator>> (istream& inStream, Student& student)
{
 ...
}

- . , Student Worker, , . , , , . < , < . , , , .

, , .

+3
4

. -, const, :

ostream& operator<< (ostream& outStream, const Person& person)

, , toString, . , .

:

class Person {
// other stuff
protected:
    virtual std::string toString();
    friend ostream& operator<< (ostream& outStream, const Person& person)
};

ostream& operator<< (ostream& outStream, Person& person)
{
    ostream << person.toString();
    return outStream;
}

Edit , larsmans :

class Person {
// other stuff
protected:
    virtual void print(ostream & stream) const;
    friend ostream& operator<< (ostream& outStream, const Person& person)
};

ostream& operator<< (ostream& outStream, Person& person)
{
    person.print(outStream);
    return outStream;
}

, toString, stringstream - .

+12

, , <<, Person, Person. (, Person), ( ), operator<< . operator<< , .

class Person {
   // ...
protected:
   virtual ostream& stream_write(ostream&) const;  //override this in child classes
   virtual istream& stream_read(istream&);        //this too
public:
   friend ostream& operator<< (ostream& stream, const Person& obj)
      { return obj.stream_write(stream); }
   friend istream& operator>> (istream& stream, Person& obj)
      { return obj.stream_read(stream); }
};
+3

. - :

struct A
{
  virtual ~A(){}

  virtual std::ostream& Print( std::ostream &os ) const
  {
    // print what you want
    return os;
  }
};

struct B : A
{
  virtual ~B(){}

  virtual std::ostream& Print( std::ostream &os ) const
  {
    // print what you want
    return os;
  }
};

< < :

std::ostream& operator<<( std::ostream &os, const A &a)
{
  return a.Print(os);
}
+2

streamIn streamOut , , streamIn streamOut.

0

Source: https://habr.com/ru/post/1774520/


All Articles