简体   繁体   中英

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.

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;}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM