Re: How to use operator overloading?
In message <hj23jv$h2j$1@newsreader3.netcologne.de>, Thomas J. Gritzan
<phygon_antispam@gmx.de> writes
Am 18.01.2010 12:32, schrieb io_x:
"io_x" <a@b.c.invalid> ha scritto nel messaggio
news:4b543a43$0$1114$4fafbaef@reader2.news.tin.it...
"osmium" <r124c4u102...@comcast.net> ha scritto nel messaggio
what about this?
#include <iostream>
using namespace std;
class intc{
public:
int datum;
While it depends on class design and purpose, your member variables
should normally be private to ensure encapsulation.
intc() {}
intc(int a){datum=a;}
Make it explicit:
explicit intc(int a) { datum = a; }
You don't want your ints to be converted into intc instances by accident.
void show() {cout << "intc datum: " << datum << endl;}
// intc operator+(intc rhs) {return datum+rhs.datum;}
intc& operator+(intc& rhs);
intc& operator-(intc& rhs);
intc& operator*(intc& rhs);
intc& operator/(intc& rhs);
friend ostream& operator<<(ostream& ost, intc& b)
{ost << b.datum << flush; return ost;}
Don't flush the stream after every output of a value. It negates the
effect of buffering and kills performance.
Besides, operator<< isn't the place to terminate lines. It should
follow the model of operator<<(ostream&, int) and do the minimum
necessary to stream a representation of the value. Layout issues like
newlines, other whitespace and punctuation are the responsibility of the
caller, and shouldn't be pre-empted by this operator.
--
Richard Herring