Classes and class hierarchies
C.160
Define operators primarily to mimic conventional usage
Reason
Minimize surprises.
Example
class X {
public:
// ...
X& operator=(const X&); // member function defining assignment
friend bool operator==(const X&, const X&); // == needs access to representation
// after a = b we have a == b
// ...
};
Here, the conventional semantics is maintained: Copies compare equal.
Example, bad
X operator+(X a, X b) { return a.v - b.v; } // bad: makes + subtract
Note
Non-member operators should be either friends or defined in the same namespace as their operands. Binary operators should treat their operands equivalently.
Enforcement
Possibly impossible.