Another C++ tip

October 29th 2004 03:12 am

Someone asked a question on #kde-devel the other day, wondering what the best way to do a stream insertion operator was. Their first suggestion was to do something like the following:

class Foo {
ostream &operator
};

The major problem is that it wouldn’t compile that way. Even if it did,
you wouldn’t be able to string insertions together like you can with cout or
kdDebug().

There are two well-known ways of fixing this, both of which involve non-member functions:

  • The first way is typically to make the operator
  • The other way is described in a book I read, and it also involves an external function, although it doesn’t need to be a friend.

Basically a class defines a virtual public method called print which accepts an output stream (e.g. ostream, QDataStream, etc) and is responsible for inserting itself onto that stream. Then the external stream simply calls the print() method and immediately returns the stream. Example:

class Foo {
public:
virtual void print(ostream &o) const {
    /* output onto o */
}
};

ostream &operator
    x.print(o);
    return o;
}

So there you go, my monthly C++ tidbit. :-)

Posted by mpyne under Uncategorized |

Trackback URI | Comments RSS

Leave a Reply


For spam filtering purposes, please copy the number 2090 to the field below This message appears because you have JavaScript disabled or your browser does not support CSS, a standard web feature.