c++ - member binary operator and nonmember binary operator in operator overloading -


while trying learning operator overloading, read following statements c++ primer. frankly speaking, not quite understand message these statements want deliver. examples include defining both member binary operator , nonmember binary operator. there difference when using them?

ordinarily define arithmetic , relational operators nonmember functions , define assignment operators members:

sales_item& sales_item:: operator (const sales_item&) sales_item operator_(const sales_item&, const sales_item&); 

both addition , compound assignment binary operators, yet these functions define different number of parameters. reason discrepancy pointer.

yes, there difference in actual use. in particular, when overload operator non-member function, conversions can applied either operand (or both operands). when overload binary operator member function, conversions can applied right operand.

this can lead oddities. example, consider writing "bignum" package , wanted overload operator+ handle bignums. if overload member function, oddity this:

int x = 2; bignum y = 3; bignum z;  z = y + x; // works fine. z = x + y; // doesn't work: x isn't bignum, , can/won't converted 1 

if, instead, overload operator+ using non-member function, both of operations work (presuming have constructor create bignum int, you'd want).

a few operators (particularly assignment operators, such =, +=, -=, etc.) special. conversion creates temporary object, , assigning temporary object 1) isn't allowed, , 2) wouldn't make sense or accomplish anyway. therefore, when you're overloading assignment operators, use member function.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -