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 <2> Overload as Friend function