第五周小作业———complex类的实现

#include<iostream>
#include<cmath>
using namespace std;
 class complex{
     public:
      complex (double real0,double imag0=0);
     complex (complex & c);     
     void add(complex d);
     double mod();     
      void show();
     private:
      double real;
      double imag;
 }; 
  
  
     complex::complex(double real0,double imag0)
     { 
         real=real0;
         imag=imag0;
     }
     
     
    complex::complex(complex &c)
    {
        real=c.real;
        imag=c.imag;
    }
    
    
    void complex::add(complex d)
    {
        real=real+d.real;
        imag=imag+d.imag;
     } 
     
     
     void complex::show()
     {
         if(real==0)
         {
             if(imag!=0)
             cout<<imag<<"i"<<endl;
             else
             cout<<0<<endl;
         }
         else
         {
             if(imag==0)
             {
                 cout<<real<<endl;
             }
            else
            {
                cout<<real<<"+"<<imag<<"i"<<endl;
            }
         }
     }
     
     
     double complex::mod()
     {
         double m;
         m=sqrt(real*real+imag*imag);
         return m;    
     }
     int main()
{
    complex c1(3,5);
    complex c2(4.5);
    complex c3(c1);
    c1.add(c2);
    c1.show();
    cout<<c3.mod()<<endl;
    return 0;
}

反思:

在这道题中遇到了一个问题,如图:

1.一开始编译后系统报错了下面这个错误,然后不明白哪里错了,百度后才知道问题出在哪里,如两个红圆圈所示,在声明构造函数时为它参数初始化了,然后在定义时又把这个初始化值写了一边,这是不可以的。

2.通过这个题目更清楚地明白了类和对象的联系。

posted @ 2019-03-31 13:00  21savage  阅读(139)  评论(0)    收藏  举报