一个c++运算符重载问题,希望得到完整代码

题目如下:
已知一个有理数类zrf_Ratio,包含私有数据成员:分子num和分母den, 以及公有函数成员

friend ostream& operator<<(ostream& ostr, const zrf_Ratio& r)

{ return ostr << r.num << "/" << r.den;}

请补充该类的构造函数,并实现如下的操作符重载形式:

friend zrf_Ratio operator-(const zrf_Ratio&);

friend zrf_Ratio operator+(const zrf_Ratio&, const zrf_Ratio&);

friend zrf_Ratio operator-(const zrf_Ratio&, const zrf_Ratio&);

friend zrf_Ratio operator*(const zrf_Ratio&, const zrf_Ratio&);

friend zrf_Ratio operator/(const zrf_Ratio&, const zrf_Ratio&);

先计算最大公约数和最小公倍数,剩下的都是数学问题了吧~

看来又是作业题了
建议你还是自己去做,有具体的问题再来

先把自己的答案拿出来看看。

楼下旁观者,求做题思路啊 ~~~~(>_<)~~~~

自己写的,求指出不足,谢谢~

#include<iostream>
#define p(x)    cout<<#x "="<<x<<endl;
using namespace std;
int min_divisor(int x,int y)    {
    while(x%y!=0)   {
        int c=y;
        y=x%y;
        x=c;
    }
    return y;
}
class zrf_Ratio {
    int num,den;
    void isLegal()const {//判断有理数是否合法 
        if(den==0)  { cout<<"分母不能为零!"<<endl;    exit(1); }
    }
public:
    zrf_Ratio(int _num=1,int _den=1):num(_num),den(_den)
    { isLegal(); }
    friend ostream& operator<<(ostream& ostr, const zrf_Ratio& r)
    { return ostr << r.num << "/" << r.den; }
    friend zrf_Ratio operator-(const zrf_Ratio& z)  { 
        z.isLegal();
        return zrf_Ratio(-z.num,z.den);
    }
    friend zrf_Ratio operator+(const zrf_Ratio& l, const zrf_Ratio& r)  {
        l.isLegal(); r.isLegal();
        int d=min_divisor(l.den,r.den);
        int new_num=(l.num*r.den+r.num*l.den)/d;
        int new_den=l.den*r.den/d;
        return zrf_Ratio(new_num,new_den);
    }
    friend zrf_Ratio operator-(const zrf_Ratio& l, const zrf_Ratio& r)  {
        l.isLegal(); r.isLegal();
        int d=min_divisor(l.den,r.den);
        int new_num=(l.num*r.den-r.num*l.den)/d;
        int new_den=l.den*r.den/d;
        return zrf_Ratio(new_num,new_den);      
    }
    friend zrf_Ratio operator*(const zrf_Ratio& l, const zrf_Ratio& r)  {
        l.isLegal(); r.isLegal();
        int new_num=l.num*r.num, new_den=l.den*r.den;
        int d=min_divisor(new_num,new_den);
        while(d!=1)
        { new_num/=d; new_den/=d;d=min_divisor(new_num,new_den); }
        return zrf_Ratio(new_num,new_den);
    }
    friend zrf_Ratio operator/(const zrf_Ratio& l, const zrf_Ratio& r)  
    { return l*(zrf_Ratio(r.den,r.num));}
};
int main()
{
    zrf_Ratio a(1,18);
    zrf_Ratio b(11,24);
    p(-a);
    p(a+b);
    p(a-b);
    p(a*b);
    p(a/b);
    zrf_Ratio e(0,1);
    p(a/e);
}

先把自己的答案拿出来看看。