complex类

#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 zhen;
        double xu;
}; 
complex::complex(double a,double b)
{
    zhen=a;
    xu=b;
}
complex::complex(complex &p)
{
    zhen=p.zhen;
    xu=p.xu;
}
void complex::show()
{
    if(zhen!=0)
    {
        if(xu!=0)
            cout<<zhen<<'+'<<xu<<'i'<<endl;
        else
            cout<<zhen<<endl;
    }
    else
    {
        if(xu!=0)
            cout<<xu<<'i'<<endl;
        else
            cout<<0<<endl;
    }
}
void complex::madd(complex q)
{
    zhen+=q.zhen;
    xu+=q.xu;
}
double complex::mod()
{
    double x,y;
    x=zhen*zhen+xu*xu;
    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;
}

add在开始的时候想写在类的外面,然后发现不会写,想问老师如何调用类里面的数。

 

posted on 2019-03-30 23:40  吵闹机器人  阅读(134)  评论(2编辑  收藏  举报