Marcin Vorbrodt wrote:
I see a lot of source code where some operators are defined as class
members, and some as friends, or just outside the class. Can someone please
explain what the general rule of thumb is? I understand that operators like
== or != can/should be definced outside of the class in order to be
symetric. What about all the other ones? I read somewhere that only the
operators that need to modify theri lvalue should be members... what are
those operators? Please help.
Thanx,
Martin
As for operator= (assignment), it is defined inside the class.
As far as others, it depends. Some authors (Scott Meyers for one),
state that some methods defined as non-member functions actually
improve encapsulation. Others state that the methods should be
defined as member functions.
I suggest defining fundamental operators as class methods, such as
operator== (equality) and operator< (less than). Other operators,
can be declared as non-member functions, such as operator!=
and operator<= (which can be defined in terms of operator== and
operator<, respectively). These operators can be defined using
templates for any type that supports the fundamental operators:
template <AnyClass>
bool operator!=(const AnyClass& a, const AnyClass& b)
{
return !(a == b);
// or return !a.operator==(b);
}
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library