Peter Meier said:
Stroustrup says he prefer's to declare operators, which do not do anything
on the class itself global. Does anybody know the reason for that?
Any advantages/disadvantages?
Advantage is the possibility to use the implicit conversions that
are often defined by the class itself.
Example 1 (member):
class A
{
int i;
public:
A(int ii) : i(ii) {}
bool operator ==(A const& a) const { return i == a.i; }
};
int main()
{
A a1(42), a2(73);
a1 == a2; // works fine
a1 == 12; // works fine, '12' is converted into a temporary A
666 == a2; // ERROR doesn't work, '666' cannot be converted
}
Example 2 (non-member)
class A
{
int i;
public:
A(int ii) : i(ii) {}
int get() const { return i; }
};
bool operator ==(A const& a1, A const& a2)
{
return a1.get() == a2.get();
}
int main()
{
A a1(42), a2(73);
a1 == a2; // works fine
a1 == 12; // works fine, '12' is converted into a temporary A
666 == a2; // works fine, '666' is converted into a temporary A
}
I am surprised that you didn't find Dr.Stroustrup's explanation as to
why non-members are better.
Victor