1. 程式人生 > >第九周專案一:複數類中的運算子過載(續)

第九周專案一:複數類中的運算子過載(續)

問題及程式碼:

在複數類中的運算子過載基礎上
(1)再定義一目運算子 -,-c相當於0-c。
(2)定義Complex類中的<<和>>運算子的過載,實現輸入和輸出,改造原程式中對運算結果顯示方式,使程式讀起來更自然。

解決程式碼:

#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(){real=0;imag=0;}
    Complex(double r,double i){real=r; imag=i;}
    Complex operator+(const Complex &c2);
    Complex operator-(const Complex &c2);
    Complex operator*(const Complex &c2);
    Complex operator/(const Complex &c2);
    Complex operator-();
    friend ostream& operator << (ostream&,const Complex&);
    friend istream& operator >> (istream&,Complex&);
private:
    double real;
    double imag;
};
//下面定義成員函式
//複數相加: (a+bi)+(c+di)=(a+c)+(b+d)i.
ostream& operator << (ostream& output,const Complex& c)
{
    output<<"("<<c.real<<","<<c.imag<<"i)";
    return output;
}
istream& operator >> (istream& input,Complex& c)
{
    cout<<"please input real part and imaginary part:";
    input>>c.real>>c.imag;
    return input;
}
Complex Complex::operator+(const Complex &c2)
{
    Complex c;
    c.real=real+c2.real;
    c.imag=imag+c2.imag;
    return c;
}
//複數相減:(a+bi)-(c+di)=(a-c)+(b-d)i.
Complex Complex::operator-(const Complex &c2)
{
    Complex c;
    c.real=real-c2.real;
    c.imag=imag-c2.imag;
    return c;
}
//複數相乘:(a+bi)(c+di)=(ac-bd)+(bc+ad)i.
Complex Complex::operator*(const Complex &c2)
{
    Complex c;
    c.real=real*c2.real-imag*c2.imag;
    c.imag=imag*c2.real+real*c2.imag;
    return c;
}

//複數相除:(a+bi)/(c+di)=(ac+bd)/(c^2+d^2) +(bc-ad)/(c^2+d^2)i
Complex Complex::operator/(const Complex &c2)
{
    Complex c;
    c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
    c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
    return c;
}
int main()
{
    Complex c1,c2,c3;
    cin>>c1>>c2;
    cout<<"c1="<<c1<<endl;
    cout<<"c2="<<c2<<endl;
    c3=c1+c2;
    cout<<"c1+c2="<<c3<<endl;
    c3=c1-c2;
    cout<<"c1-c2="<<c3<<endl;
    c3=c1*c2;
    cout<<"c1*c2="<<c3<<endl;
    c3=c1/c2;
    cout<<"c1/c2="<<c3<<endl;
    return 0;
}

執行結果:

學習心得:運用到了過載單目運算子,還有流插入運算子和流提取運算子,感覺過載了流插入運算子和流提取運算子後程序更加簡明清晰了!