Differences between non-member operators and member operators

Source: Internet
Author: User

We generally use the following two methods to overload operators:

  1. Member Functions
  2. Non-member functions

In fact, these two definitions are not only syntactic, but also semantic. In syntax, it is defined as a member function, such as operator + =. Only one parameter is accepted, and a non-member function accepts two parameter semantics. This involvesThe temporary object cannot be bound to the left-side reference.For example, we need to reload operator ++ =, operator ++

struct foo{#ifndef NON_MEMBER_OPERATOR    foo& operator +=(const foo& rhs)    {        return *this;    }    foo& operator ++()    {        return *this;    }#endif};#ifdef NON_MEMBER_OPERATORfoo& operator +=(foo& lhs, const foo& rhs){    return lhs;}foo& operator ++(foo& lhs){    return lhs;}#endif

Here, if we use a member function, we can call operator ++ = or operator ++ on a temporary object.

foo() += foo();++foo();

This statement can be compiled. But in general, we do not want to modify the temporary object, because the modification is usually lost with the destruction of the temporary object. When a non-member function is used, the preceding statement cannot be compiled because the temporary object cannot be bound to the left value reference. This is generally in line with our requirements and is easier to prevent misuse. Therefore, for mutating Operator overloading, we prefer the form of non-member functions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.