回覆列表
  • 1 # 錢布斯

    #include<iostream.h>

    class complex //複數類宣告

    { public: //外部介面

    complex(double r=0.0,double i=0.0) //建構函式

    {real=r;imag=i;}

    complex operator +(complex &c2); //運算子"+"過載成員函式

    complex operator /(int c); //運算子"/"過載成員函式

    complex operator =(complex &c2); //運算子"="過載成員函式

    void display(); //輸出複數

    void get();

    private: //私有資料成員

    double real; //複數實部

    double imag; //複數虛部

    };

    complex complex::operator +(complex &c2)

    {

    double r,i;

    r=real+c2.real;

    i=imag+c2.imag;

    return complex(r,i);

    }

    complex complex::operator /(int c)

    {

    return complex(real/c,imag/c);

    }

    /*運算子"="過載成員函式*/

    complex complex::operator =(complex &c2)

    {

    real = c2.real;

    imag = c2.imag;

    return *this;

    }

    void complex::display()

    {

    cout<<"("<<real<<","<<imag<<"i)"<<endl;

    }

    void complex::get()

    {

    cin>>real;

    cin>>imag;

    }

    int main()

    {

    int i;

    complex c[3];

    for(i=0;i<3;++i)

    {

    cout<<"輸入第"<<i+1<<"個複數:";

    c[i].get();

    }

    cout<<"和為";

    (c[0]+c[1]+c[2]).display();

    cout<<"平均值為:";

    ((c[0]+c[1]+c[2])/3).display();

    return 0;

    }這是體現C++風格的,你需要簡單的,再追問吧……

  • 中秋節和大豐收的關聯?
  • 生肖屬豬人取名宜用哪些字?