代码改变世界

Complex类的实现

2019-04-01 23:42  孙乾(小U)  阅读(170)  评论(1编辑  收藏  举报
#include<iostream>
#include<cmath> 
using namespace std;
class complex{
    public:
        complex(double a,double b=0);
        complex(complex &p);
        void show();
        void madd(complex q);
        double mod();
    private:
        double real;
        double imag;
}; 
complex::complex(double a,double b)
{
    real=a;
    imag=b;
}
complex::complex(complex &p)
{
    real.p.real;
    imag=p.imag;
}
void complex::show()
{
    if(real!=0)
    {
        if(imag!=0)
            cout<<real<<'+'<<imag<<'i'<<endl;
        else
            cout<<real<<endl;
    }
    else
    {
        if(imag!=0)
            cout<<imag<<'i'<<endl;
        else
            cout<<0<<endl;
    }
}
void complex::madd(complex q)
{
    real+=q.real;
    imag+=q.imag;
}
double complex::mod()
{
    double x,y;
    x=real*real+imag*imag;
    y=sqrt(x);
    return y;
}
int main()
{
    complex c1(3,5);
    complex c2(4.5);
    complex c3(c1);
    c1.show();
    c2.show();
    c3.show();
    cout<<c3.mod()<<endl;
    c1.madd(c2);
    c1.show();
    return 0;
}