C + + overloaded operators

Source: Internet
Author: User

Two ways of operator overloading

For many operators, you can choose to use member functions or non-member functions to implement operator overloading. In general, a non-member function should be a friend function so that the private data of the class can be accessed directly. For example, the addition operator of the time class is prototyped in the time class declaration:

Time operator+ (const time &t) Const;//member version

The way this member function is declared.

The declaration of this function can also make the way of the UF meta-function:

Friend Time operator+ (const time &T1, const time &T2)//nonmember version

  

The addition operation requires two operands, and for the member function version, an operand is implicitly passed through the this pointer, and the other operand is passed explicitly as a function parameter, and for the version of the friend function, two operands are passed as parameters.

Both prototypes match the expression T2 + T3, where both T2 and T3 are time type objects. In other words, the compiler will use the following statement:

T1 = T2 + T3; Convert to any of the following: T1 = t2.operator+ (T3);//member functionT1 = operator+ (T2, T3);//nonmember function

Remember that when you select an operator, you must select one of these formats, and you cannot select both. Because both formats match the same expression, defining both of these formats is considered a ambiguity error, resulting in a compilation error.

So which is the best format? For some operators, the member function is the only valid choice, such as the self-increment operator++ operation, the operator= operation. In other cases, the two formats are not much different.

return type for operator overloading

C + + overloaded operators

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.