运算符重载----有理数类

/*
定义一个有理数类Rational,重载算术运算符。写一个完整的程序,测试各种运算符的使用,要求输出化简后的计算结果,注意分母不能为零!
测试代码样例:
    Rational A(2,6),B(1,-2),C;
    C = -A;  
	C.print( );//输出1/3   
    C = A + B ;  
	C.print( );  //输出-1/6
    C = C*A/B;  
	C.print( );   
    C =  ++A ;   
	A.print( ); 
	C.print( ); 
    C =  B-- ;    
	B.print( );
	C.print(  );

*/
#include
class Rational
{
public:
    Rational(int nn=1,int mm=1);
    void print();
	void simple();  
	
	Rational  operator+(Rational & a);	//加法
	friend  Rational  operator-(Rational & a,Rational & b);//减法
	friend  Rational  operator*(Rational & a,Rational & b);//乘法
	friend  Rational  operator/(Rational & a,Rational & b);//除法
	Rational  operator-();//取反
    Rational &  operator ++ ();//r=++r1
	Rational  operator ++ (int);//r = r1++
	Rational &  operator -- ();//r=--r1
	Rational  operator -- (int);//r = r1--

    operator double();
	friend ostream& operator<<(ostream& output, Rational& a);
	bool operator<(Rational &);
    friend bool operator==(Rational& ,Rational& );
 
  private:
    int m;   // 分母 
	int n;   // 分子
};

Rational:: Rational(int nn,int mm )
{
	m= (mm!=0) ? mm:1;
	n=nn; 
}
// r = r1 + r2 ; 
Rational Rational::operator+(Rational & A)
{
	Rational C;
	C.n = n*A.m+m*A.n;
	C.m = m*A.m;
	C.simple();
	return C;
}
Rational Rational::operator-()
{  
	Rational C(-n,m); 
	C.simple();
	 return C;
}
// r = r1 - r2 ; 
Rational operator-(Rational & A,Rational & B)
{
	Rational C;
	C.n = A.n*B.m-A.m*B.n;
	C.m = A.m*B.m;
	C.simple();
	return C;
}
// r = r1 * r2 ; 
Rational operator*(Rational & A,Rational & B)
{
	Rational C;
	C.n = A.n*B.n;
	C.m = A.m*B.m;
	C.simple();
	return C;
}
// r = r1 / r2 ; 
Rational operator/(Rational & A,Rational & B)
{
	Rational C;
	C.n = A.n*B.m;
	C.m = A.m*B.n;
	C.simple();
	return C;
}
//r = ++r1;
Rational&  Rational::operator++()
{ 
	n = n+m;
	return *this;
}
//r = r1++;
Rational Rational::operator++(int)
{ 
	Rational C(n,m);
	n+=m;
 	return C; 
}
//r = --r1;
Rational&  Rational::operator--()
{ 
	n = n-m;
	return *this;
}
//r = r1--;
Rational Rational::operator--(int)
{ 
	Rational C(n,m);
	n-=m;
 	return C; 
}
Rational::operator double()
{
	return (double)n/m;  
}
// r1>r2
bool Rational::operator<(Rational& a)
{
	return double(n)/m >(double)a.n/a.m ? true : false;
}
//r1==r2
bool operator==(Rational& a,Rational&b )
{
	return double(a.n)/a.m == (double)b.n/b.m ? true : false;
}
//cout<

运算符重载----有理数类_第1张图片

你可能感兴趣的:(C++程序设计--原创+转载)