Dušan Jovanović
Dušan Jovanović

Reputation: 23

Overloading I/O operators with a non-friend method in C++ | &istream and &ostream functions

So, my problem is that I need to make my &istream and &ostream functions (operators) in class virtual. And for that I need to make them class's own methods rather than friend functions like:

friend istream& operator>>(istream&, const String&);
friend ostream& operator<<(ostream&, const String&);

So, how to write these methods in the class itself without using friend functions? I would only need the prototypes for my header, I can write the bodies on my own, I'm just confused with the parameters.

Btw "String" is an object type defined elsewhere.

Upvotes: 1

Views: 466

Answers (2)

Columbo
Columbo

Reputation: 60999

Perhaps like this:

class String
{
public:

    virtual void read(istream& is) { /* […] */ }
    virtual void print(ostream& os) const { /* […] */ }
};

istream& operator>>(istream& is, String& s)
{s.read (is); return is;}

ostream& operator<<(ostream& os, const String& s)
{s.print(os); return os;}

Upvotes: 1

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153955

Just create [virtual] member functions read() and write() each taking a corresponding stream and call them from the respective operator:

class String {
    // ...
public:
    virtual std::istream& read(std::istream& in);
    virtual std::ostream& write(std::ostream& out) const;
};
std::istream& operator>> (std::istream& in, String& s) {
    return s.read(in);
}
std::ostream& operator<< (std::ostream& out, String const& s) {
    return s.write(out);
}

Upvotes: 1

Related Questions