• c++运算符重载


    代码:

    #include<iostream>
    #include<cstdio>
    using namespace std;
    class complex
    {
        int x,y;
    public:
        complex(int a=0,int b=0)
        {
            x=a;
            y=b;
        }
        void print();
        friend complex operator + (complex a,complex b);
        friend complex operator - (complex a,complex b);
        friend complex operator * (complex a,complex b);
        friend complex operator / (complex a,complex b);
    }; 
    int gcd(int a,int b)
    {
        return b==0?a:gcd(b,a%b);
    }
    void complex::print()
    {
        if(x==y||x==0)
            cout<<x<<endl;
        else
            cout<<x<<"/"<<y<<endl;
    }
    complex operator + (complex a,complex b)
    {
        complex temp;
        temp.x=a.x*b.y+b.x*a.y;
        temp.y=a.y*b.y;
        int g=gcd(temp.x,temp.y);
        temp.x/=g;
        temp.y/=g;
        return temp;
    }
    complex operator - (complex a,complex b)
    {
        complex temp;
        temp.x=a.x*b.y-b.x*a.y;
        temp.y=a.y*b.y;
        int g=gcd(temp.x,temp.y);
        temp.x/=g;
        temp.y/=g;
        return temp;
    }
    complex operator * (complex a,complex b)
    {
        complex temp;
        temp.x=a.x*b.x;
        temp.y=a.y*b.y;
        int g=gcd(temp.x,temp.y);
        temp.x/=g;
        temp.y/=g;
        return temp;
    }
    complex operator / (complex a,complex b)
    {
        complex temp;
        temp.x=a.x*b.y;
        temp.y=a.y*b.x;
        int g=gcd(temp.x,temp.y);
        temp.x/=g;
        temp.y/=g;
        return temp;
    }
    int main()
    {
        ios::sync_with_stdio(false); 
        int num;
        while(cin>>num)
        {
            while(num--)
            {
                int aa,bb,cc,dd;
                char e,g;
                cin>>aa>>e>>bb>>cc>>g>>dd;
                complex c1(aa,bb),c2(cc,dd),c3;
                c3=c1+c2;
                c3.print();
                c3=c1-c2;
                c3.print();
                c3=c1*c2;
                c3.print();
                c3=c1/c2;
                c3.print();
            }
        }
        return 0;
    }

    今天也是元起满满的一天!good luck!

  • 相关阅读:
    Some good websites for C++
    Static Class in C#
    js提示后跳转代码集合
    日期格式化函数
    URL伪静态
    正则的一些使用
    提高.net网站的性能
    验证DropDownList的方法
    用C#去除字符串中HTML的格式
    drepdownlist不能动态绑定数据的原因
  • 原文地址:https://www.cnblogs.com/cattree/p/7856832.html
Copyright © 2020-2023  润新知