C ++ operator reload notes
Today I read the operator overload in c ++ and record it for later viewing:
# Include
Using namespace std; class F {int n; int d; void reduce () {int mcd = maxcd (n <0? -N: n, d); if (mcd! = 1) {n/= mcd; d/= mcd;} public: F (int n = 0, int d = 1): n (n), d (d) {if (d = 0) throw "the 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, );} friend ostream & operator <(ostream & o, const F & f) {o <f. n <'/' <f. d; return o;} friend F operator + (const F & lh, const F & rh) {retur N F (lh. n * rh. d + lh. d * rh. n, lh. d * rh. d);} // member function, with one parameter missing (the current object acts as the first operand) F operator * (const F & rh) const {// 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:
1. Anonymous objects
2. Differences between member functions and friend functions on Operator Overloading
3. Temporary variables can only be passed to reference constants (const F &). For example, in f1 + f2 + f3, f1 + f2 returns a temporary variable.
4. You can implement the functions either inside the class or outside the class.
5. When const is added to a method, it indicates that the object indicated by this in the method can only be read and cannot be modified.