A preliminary study of C + + operator overloading Learning notes <2> Overload as Friend function

Source: Internet
Author: User

A preliminary study on C + + operator overloading Learning notes

In the previous blog, we wrote about overloading operators with normal functions or member functions of classes .

The following two conditions occur. Then we need to overload the operator with the friend function of the class

<1> member functions do not meet the requirements

<2> Normal functions cannot access private members of a class

To illustrate:

Class complex{    double Real, imag;    Public:    Complex (Double R, double i): Real (R), Imag (i) {};     Complex operator+ (Double R);   };    Complex complex::operator+ (Double r) {    return Complex (real + R, imag);}

Defines a complex number class. Overloaded ' + ' operators, after overloading

Complex C = c + 5;  There is a definition, equivalent to C = C.operator + (5);

However, if 5+c is present, the compilation problem occurs. You also need to overload the normal function at this point.

Complex operator+ (Double R, const Complex & c) {    return Complex (C.real + R, C.imag);}


Can explain 5+c, but the normal function cannot access the private members of the class.

In this case, you need to overload the friend function for the class

Class Complex {    double real, imag;    Public:    Complex (Double R, double i): Real (R), Imag (i) {};     Complex operator+ (Double R);    Friend Complex operator + (double R, const Complex & c);};



A preliminary study of C + + operator overloading Learning notes &lt;2&gt; Overload as Friend function

Related Article

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.