V
Victor Bazarov
Rob said:Victor Bazarov wrote in @newsread1.dllstx09.us.to.verio.net in comp.lang.c++:
Richard said:In message <[email protected]>, "Niels Dekker (no reply
[...]
In what situation would you prefer to implement a binary
operator as a member function?
If the function modifies its argument (e.g. operator+= above.).
Operator += is an assignment operator and it cannot be implemented as
a non-member, no matter whether it in fact modifies its left operand
or not (and it is up to you to decide whether it does modify it).
#include <iostream>
#include <ostream>
struct X {};
X &operator += ( X &lhs, X const & )
{
std::cout << "Ok" << std::endl;
return lhs;
}
int main()
{
X a, b;
a += b;
}
Works fine for me.
Perhaps it's my misreading of the Standard. First it calls all @=
operators "assignment operators" (@ denotes an operation like + or -)
then it says that the assignment operator has to be a member, but when
it gives an example it only speaks of operator=. Does that mean that
operators like += don't have to be members? Perhaps that's open to
interpretation. Perhaps not. I will ask for clarification in the
standard newsgroup.
Also operator ->(), I can't remember any others (*).
*) Ok, new and delete, but I don't think they count .
They are actually static, while not declared so. Very unusual.
V