C + + operator overloading notes

Source: Internet
Author: User

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

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.