C ++ operator reload notes

Source: Internet
Author: User

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.


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.