1. Operator overloading
2, Class of packaging
#include <stdio.h>#include<algorithm>#include<iostream>using namespacestd;intgcdintMintN///Beg Greatest common divisor{ if(n==0) returnm; Else returnGCD (n,m%n);}classfraction{ Public: fraction (); Fraction (intAintb): molecule (a), denominator (b) {}voidSetData (); voiddisplay (); Fractionoperator* (Fraction &a) {fraction C; intTemp1;///molecule intTemp2;///Denominator intL///Greatest Common Divisortemp1= This->molecule*A.molecule; Temp2= This->denominator*A.denominator; L=gcd (TEMP1,TEMP2); C.molecule=temp1/m; C.denominator=temp2/m; returnC; } Fractionoperator+ (Fraction &a) {fraction C; intTemp1;///molecule intTemp2;///Denominator intL///Greatest Common Divisortemp1= This->molecule*a.denominator+ This->denominator*A.molecule; Temp2= This->denominator*A.denominator; L=gcd (TEMP1,TEMP2); C.molecule=temp1/L; C.denominator=temp2/m; returnC; } Fractionoperator-(Fraction &a) {fraction C; intTemp1;///molecule intTemp2;///Denominator intL///Greatest Common Divisortemp1= This->molecule*a.denominator- This->denominator*A.molecule; Temp2= This->denominator*A.denominator; L=gcd (TEMP1,TEMP2); C.molecule=temp1/m; C.denominator=temp2/m; returnC; } Fractionoperator/(Fraction &a) {fraction C; intTemp1;///molecule intTemp2;///Denominator intL///Greatest Common Divisortemp1= This->molecule*A.denominator; Temp2= This->denominator*A.molecule; L=gcd (TEMP1,TEMP2); C.molecule=temp1/m; C.denominator=temp2/m; returnC; }Private: intmolecule;///molecule intdenominator;///Denominator}; Fraction::fraction () {molecule=0; Denominator=1;}voidFraction::setdata () {cin>>molecule>>denominator;}voidfraction::d isplay () {cout<<molecule<<"/"<<denominator<<Endl;}intMain () {fraction a,b,c; printf ("This is fraction ' s operation\n"); printf ("Please input your wants fraction ' s operation\n"); Charo; scanf ("%c",&o); System ("CLS"); Switch(o) { Case '+': printf ("Please input fraction ' s molecule and imag\n"); A.setdata (); B.setdata (); C=a+b; C.display (); Break; Case '-': printf ("Please input fraction ' s molecule and imag\n"); A.setdata (); B.setdata (); C=a-b; C.display (); Break; Case '*': printf ("Please input fraction ' s molecule and imag\n"); A.setdata (); B.setdata (); C=a*b; C.display (); Break; Case '/': printf ("Please input fraction ' s molecule and imag\n"); A.setdata (); B.setdata (); C=a/b; C.display (); Break; } System ("Pause"); return 0;}
Calculation of fractions