简体   繁体   中英

When should I use non-member operator overloading?

Should I be using non-member overload or member overload? How do I tell which I should use?

If you're thinking about something like operator< or swap , there's a rule of thumb ( though it's not terribly strict or mandatory):

If the function only requires access to the public interface of your class, make it a free non-member function. Otherwise make it a member function. (Alternatively you may consider a friend free function.)

Note that for overloads of operators you will need at least one of the operands to be a user-defined type.

The design advantage of a free function is that you can make it a template and get M + N complexity rather than M * N if you were to implement a version of the operator for each class for which it's applicable. This may or may not be relevant to your situation.

See also Nawaz's very fine answer on the subject.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM