实现分数类中的运算符重载,在分数类中可以完成分数的加减乘除(运算后再化简)、求反、比较(6种关系)的运算。
#include<iostream>
#include<cmath>
using namespace std;
class CFraction
{
private:
int nume;
int deno;
public:
CFraction(int n=0, int d=1) : nume(n), deno(d){}
CFraction operator + (CFraction &);
CFraction operator - (CFraction &);
CFraction operator * (CFraction &);
CFraction operator / (CFraction &);
CFraction operator -();
void display();
bool operator > (CFraction &);
bool operator < (CFraction &);
bool operator == (CFraction &);
};
CFraction CFraction::operator + (CFraction &a )
{
CFraction n;
n.nume = a.deno * nume + a.nume * deno;
n.deno = deno * a.deno ;
return n;
}
CFraction CFraction::operator - (CFraction &a)
{
CFraction n;
n.nume = a.deno * nume - a.nume * deno;
n.deno = deno * a.deno ;
return n;
}
CFraction CFraction::operator / (CFraction &a)
{
CFraction n;
n.nume = nume * a.deno ;
n.deno = deno * a.nume ;
return n;
}
CFraction CFraction::operator * (CFraction &a)
{
CFraction n;
n.nume = nume * a.nume ;
n.deno = deno * a.deno ;
return n;
}
CFraction CFraction::operator -()
{
CFraction n;
n.nume = -nume;
n.deno = deno;
return n;
}
void CFraction::display()
{
int m, n, r, a, b;
a = abs(nume);
b = abs(deno);
if( a > b)
{
m = a;
n = b;
}
else
{
m = b;
n = a;
}
r = m % n;
while( r != 0)
{
m = n;
n = r;
r = m % n;
}
nume = nume / n;
deno = deno / n;
cout << nume << "/" << deno << endl;
}
bool CFraction::operator > (CFraction &a)
{
if( a.deno * nume > a.nume * deno)
{
return true;
}
else
{
return false;
}
}
bool CFraction::operator < (CFraction &a)
{
if( a.deno * nume < a.nume * deno)
{
return true;
}
else
{
return false;
}
}
bool CFraction::operator == (CFraction &a)
{
if( a.deno * nume < a.nume * deno)
{
return true;
}
else
{
return false;
}
}
int main()
{
CFraction c1(1,2), c2(1,3), c3;
cout << "c1=";
c1.display ();
cout << "c2=";
c2.display ();
if( c1 > c2) cout << "c1>c2" << endl;
if( c1 < c2) cout << "c1<c2" << endl;
if( c1 == c2) cout << "c1=c2" << endl;
cout << "-c1 = ";
c3 = -c1;
c3.display ();
cout << "c1+c2=";
c3 = c1 + c2;
c3.display ();
cout << "c1-c2=";
c3 = c1 - c2;
c3.display ();
cout << "c1*c2=";
c3 = c1 * c2;
c3.display ();
cout << "c1/c2=";
c3 = c1 / c2;
c3.display ();
system("pause");
return 0;
}
还好老师手下留情<<<就让做了三个