Why must operator & lt; & gt; operator overload be a friend function ?, Operator overload

Source: Internet
Author: User

Why must operator <> operator Overloading be a friend function ?, Operator overload

If the operator is an overloaded binary operator (a member function of the class), you only need to set a parameter as the calculation amount on the right side, and the calculation amount on the left side is the object itself ......

And> or <the left side of the calculation is cin or cout rather than the object itself, so it does not meet the following requirements ........ It can only be declared as a friend function...

If it must be declared as a member function, it can only be in the following form:

Ostream & operator <(ostream & output)

{

Return output;

}

Therefore, this <operator is used in the form of data <cout;

The habit of not matching people.


Operator overload functions can be used as member functions, friend functions, and common functions.

Common functions: Generally, Private Members are indirectly accessed through public interfaces of the class.

Member function: You can use the this pointer to access the members of this class. You can write less than one parameter. However, the first parameter on the left of the expression must be a class object. You can call the member function through this class object.

Friend functions: the left side is generally not an object. <> Generally, operators must be declared as friends-element overload functions.


Generally:

The binary operator is overloaded as a friend function, so that the exchange law can be used, which is more convenient.

The single-object operator is typically overloaded as a member function, because operations are directly performed on the class object itself.


In short: If the operator overload is a member function, the first parameter must be the object of this class, because the object of the first parameter is used by default to call this member function.




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.