Given that prefix unary operators can be "implemented by a non-static member function with no parameters or a non-member function with one parameter" (§13.5.1[over.unary]/1), is there a difference besides the usual encapsulation/code reuse design rationales that apply to any member/non-member function choices?
For binary operators, there's a semantic difference because non-members allow implicit conversions of their left-hand operands. There doesn't seem to be anything like that for the unary operators, yet the standard defines std::complex
's unary negation operator as a non-member (§26.4.6[complex.ops]), while std::valarray
's and std::duration
's unary negation operators are members (§26.6.2.6[valarray.unary], §20.11.5.3[time.duration.arithmetic]). Is there a nuance?
Overload unary minus operator in C++?The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it.
Because unary operators are right associative the expression *p++ will be evaluated as *(p++) .
When unary operators are overloaded through a member function, they do not take any explicit arguments. But when overloaded by a friend function, they take one argument. When binary operators are overloaded through a member function they take one explicit argument.
As far as I'm aware there are no differences as compared to deciding if a non-operator function should be member or non-member. Obviously prefer non-member, non-friend when possible (like the standard algorithms).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With