C++——定义一个复数类Complx, 重载运算符“+”*““/”“,使之能用于复数的加,流来、原。运算符重载函数作为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+(Complex &c2);
    Complex operator-(Complex &c2);
    Complex operator*(Complex &c2);
    Complex operator/(Complex &c2);
    void display();
private:
    double real;
    double imag;
};
void Complex::display()
{
    cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
Complex Complex::operator+(Complex&c2)
{
    Complex c;
    c.real=real+c2.real;
    c.imag=imag+c2.imag;
    return c;
}
Complex Complex::operator-(Complex&c2)
{
    Complex c;
    c.real=real-c2.real;
    c.imag=imag-c2.imag;
    return c;
}
Complex Complex::operator*(Complex&c2)
{
    Complex c;
    c.real=real*c2.real-imag*c2.imag;
    c.imag=imag*c2.real+real*c2.imag;
    return c;
}
Complex Complex::operator/(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(3,4),c2(5,-10),c;
    c=c1+c2;
    cout<<"c1+c2=";
    c.display();
    c=c1-c2;
    cout<<"c1-c2=";
    c.display();
    c=c1*c2;
    cout<<"c1*c2=";
    c.display();
    c=c1/c2;
    cout<
    <"c1/c2=";
    c.display();
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/2303_80770781/article/details/143472503