#include<iostream>
using namespace std;
class complex
{
public:
complex();
complex(double ,double );
friend complex operator+(complex &c1,complex &c2);
friend complex operator-(complex &c1,complex &c2);
friend complex operator*(complex &c1,complex &c2);
friend complex operator/(complex &c1,complex &c2);
void display();
private:
double real;
double imag;
} ;
complex operator+(complex &c1,complex &c2)
{
complex c;
c.real=c1.real+c2.real;
c.imag=c1.imag+c2.imag;
return c;
}
complex operator-(complex &c1,complex &c2)
{
complex c;
c.real=c1.real-c2.real;
c.imag=c1.imag-c2.imag;
return c;
}
complex operator*(complex &c1,complex &c2)
{
complex c;
c.real=c1.real*c2.real-c1.imag*c2.imag;
c.imag=c1.imag*c2.real+c1.real*c2.imag;
return c;
}
complex operator/(complex &c1,complex &c2)
{
complex c;
c.real=(c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c.imag=(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
return c;
}
int main()
{
complex c1(3,4),c2(5,-10),c3;
c3=c1+c2;
c3.display();
c3=c1-c2;
c3.display();
c3=c1*c2;
c3.display();
c3=c1/c2;
c3.display();
return 0;
}
complex::complex()
{
real=0;
imag=0;
}
complex::complex(double r,double i)
{
real=r;
imag=i;
}
void complex::display()
{
cout<<'('<<real<<','<<imag<<"i)"<<endl;
}
复数的加减乘除法重载
最新推荐文章于 2024-09-10 19:16:08 发布