One reason to use non-member operators (typically declared as friends) is because the left-hand side is the one that does the operation. Obj::operator+
is fine for:
obj + 2
but for:
2 + obj
it won't work. For this, you need something like:
class Obj
{
friend Obj operator+(const Obj& lhs, int i);
friend Obj operator+(int i, const Obj& rhs);
};
Obj operator+(const Obj& lhs, int i) { ... }
Obj operator+(int i, const Obj& rhs) { ... }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…