定义一个复数类Complex,重载运算符+,-,*,/,使之能用于复数的加、减、乘、除。运算符重载函数作为Complex类的成员函数。编程序,分别求两个复数之和、差、积和商。

定义一个复数类Complex,重载运算符+,-,*,/,使之能用于复数的加、减、乘、除。运算符重载函数作为Complex类的成员函数。编程序,分别求两个复数之和、差、积和商。
代码如下(注:复数的乘法和除法公式请提前了解,并不是简单的实部、虚部间相乘和相除):

#include
using namespace std;
class Complex
{
    private:
            double real;//实部
            double imag;//虚部
    public:
             Complex(){real=0;imag=0;};
             Complex(double r,double i):real(r),imag(i){};
             void display();
             Complex operator+(Complex c1);//重载运算符+函数
             Complex operator-(Complex c1);//重载运算符-函数
             Complex operator*(Complex c1);//重载运算符*函数
             Complex operator/(Complex c1);//重载运算符/函数
};
void Complex::display()
{
    cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
Complex Complex::operator+(Complex c1)
{
    Complex c;
    c.real=real+c1.real;
    c.imag=imag+c1.imag;
    return c;

}
Complex Complex::operator-(Complex c1)
{
    Complex c;
    c.real=real-c1.real;
    c.imag=imag-c1.imag;
    return c;

}
Complex Complex::operator*(Complex c1)
{
    Complex c;
    c.real=real*c1.real-imag*c1.imag;
    c.imag=imag*c1.real+real*c1.imag;
    return c;

}
Complex Complex::operator/(Complex c1)
{
    Complex c;
    c.real=(real*c1.real+imag*c1.imag)/((c1.real)*(c1.real)+(c1.imag)*(c1.imag));
    c.imag=(imag*c1.real-real*c1.imag)/((c1.real)*(c1.real)+(c1.imag)*(c1.imag));
    return c;

}
int main()
{
    Complex c1(3,4),c2(5,-10),c3;
    cout<<"c1=";c1.display();
    cout<<"c2=";c2.display();
    cout<<"c3=";c3.display();
    c3=c1+c2;cout<<"c1+c2=";c3.display();
    c3=c1-c2;cout<<"c1-c2=";c3.display();
    c3=c1*c2;cout<<"c1*c2=";c3.display();
    c3=c1/c2;cout<<"c1/c2=";c3.display();
}

运行结果如下:
定义一个复数类Complex,重载运算符+,-,*,/,使之能用于复数的加、减、乘、除。运算符重载函数作为Complex类的成员函数。编程序,分别求两个复数之和、差、积和商。_第1张图片

你可能感兴趣的:(C++,c++,矩阵,开发语言)