C++实现复数类的输入输出流以及+-*/的重载

C++实现复数类的输入输出流以及+ - */的重载

 

#include <iostream>
using namespace std;
class Complex
{
public:
    Complex():real(0),image(0){}
    Complex(double a, double b):real(a),image(b){}
    operator double(){
        if(real==0&&image==0)
        return 0;
        else
        return 1;
    }
    friend Complex operator *(Complex&, Complex&);
    friend Complex operator +(Complex&, Complex&);
    friend Complex operator -(Complex&, Complex&);
    friend Complex operator /(Complex&, Complex&);
    friend ostream& operator <<(ostream&, Complex&);
    friend istream& operator >>(istream&, Complex&);
private:
    double real;
    double image;
};
Complex operator +(Complex& a, Complex& b)
{
    Complex c(a.real + b.real,a.image + b.image);
    return c;
}
Complex operator -(Complex& a, Complex& b)
{
    Complex c(a.real - b.real,a.image - b.image);
    return c;
}
Complex operator *(Complex& a, Complex& b)
{
    Complex c(a.real * b.real - a.image * b.image, a.real * b.image + a.image * b.real);
    return c;
}
Complex operator /(Complex& a, Complex& b)
{
    double t=b.real*b.real+b.image*b.image;
    Complex c(b.real, -1*b.image);
    Complex d = a*c;
    d.real/=t;
    d.image/=t;
    return d;
}
istream& operator >>(istream& is, Complex& cp)
{
    is.clear();
    char t,t2;
    double a,b;
    t2=is.peek();
    if(t2==' '||t2=='
')
    {
        getchar();
        t2=is.peek();
    }
    is>>a;
    t=getchar();
    if(t=='i')
    {
        if(a)
        cp=Complex(0,a);
        else
        {
            if(t2=='-')
            cp=Complex(0,-1);
            else
            cp=Complex(0,1);
        }
        return is;
    }
    else if(t=='+'||t=='-')
    {
        is>>b;
        t2=getchar();
        if(b&&t=='-')
        {
           b*=-1;
        }
        if(b)
        {
             cp=Complex(a,b);
            return is;
        }
        else
        {
            if(t=='-')
             cp=Complex(a,-1);
             else
             cp=Complex(a,1);
            return is;
        }
    }
    else
    {
        cp=Complex(a,0);
        return is;
    }
}
ostream& operator <<(ostream& os, Complex& a)
{
    if (a.image > 0)
    {
        if(a.real!=0)
        {
            if(a.image!=1)
            os << a.real << "+" << a.image << "i";
            else
            os << a.real << "+" << "i";
        }
        else if(a.image==1)
        os << "i";
        else
        os << a.image << "i";
    }
    else if(a.image<0)
    {
        if (a.real != 0)
        {
            if(a.image!=-1)
            os << a.real  << a.image << "i";
            else
            os << a.real  << "-i";
        }
        else
            if(a.image!=-1)
            os << a.image << "i";
            else
            os << "-i";
    }
    else
    {
        os << a.real;
    }
    return os;
}