Today I saw operator overloading in C + + and logged it for later review:
#include <iostream>using namespace Std;class f{int n;int d;void reduce () {int mcd = MAXCD (n < 0?-n:n, D); if (MC D! = 1) {n/= mcd;d/= mcd;}} public:f (int n=0, int d=1): N (N), D (d) {if (d = = 0) Throw "denominator cannot be zero"; if (d < 0) {this->d =-this->d;this->n =-this- >n;} Reduce (); cout << "F (" << n << '/' << D << ")" << Endl; static int Maxcd (int a, int b) {if (a = = 0) return B;return maxcd (b%a, a);} Friend ostream& operator<< (ostream& o, const f& F) {o << f.n << '/' << f.d;return o;} Friend F operator+ (const f& LH, const f& RH) {return F (LH.N * Rh.d + Lh.d * RH.N, Lh.d * Rh.d);} member function, one less parameter (the current object as the first operand) F operator* (const f& RH) const{//Anonymous object return F (N*RH.N, D*rh.d);} Friend F operator~ (const f& f) {return F (f.d, F.N);} BOOL operator! () Const{return n==0;}}; int main () {F F1; F F2 (3); F F3 (6, 12); F F4 (5, 3); F f5 (2, 9); cout << f3 << ', ' << f4 << endl;cout << f::maxcd (392, 856) << endl;cout << f3 + F4 << endl;cout << f3*f4 << F2 * f3 * f4 << endl;cout << "~f3 = "<< ~f3 << endl;cout <<"!f3 = "<<!f3 << endl;return 0;}
Note the point:
1. Anonymous objects
2. Differences in operator overloading between member functions and friend functions
3, temporary variables can only be passed to the reference constant (const f&), such as F1 + F2 + F3 F1 + F2 return is a temporary variable
4. The friend function can be implemented either within the class or outside the class, not the member function of the class
5, const Plus on the method indicates that the object within the method can only read non-modifiable.
C + + operator overloading notes