Re: How to use operator overloading?
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.
};
unsigned index=0;
intc v[16];
intc& intc::operator-(intc& rhs)
{unsigned u=index;
v[u].datum=datum-rhs.datum;
++index; if(index==16) index=0;
return v[u];
}
[ same for operator+, *, / ]
What's wrong with the simple and standard approach?
intc operator+(intc const& rhs) const
{
return intc(datum + rhs.datum);
}
intc operator-(intc const& rhs) const
{
return intc(datum + rhs.datum);
}
/* [...] */
I expect return-by-value to be much faster in this case. It's easier to
understand and maintain than your code. And it is thread-safe.
--
Thomas