用类的成员函数完成运算符的重载的代码如下,请大家自己调试:
#include
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;
};
Complex Complex::operator+(Complex&c2)
{
return Complex(real+c2.real,imag+c2.imag);
}
Complex Complex::operator-(Complex&c2)
{
return Complex(real-c2.real,imag-c2.imag);
}
Complex Complex::operator*(Complex&c2)
{
return Complex(real*c2.real+imag*c2.imag,real*c2.imag+imag*c2.real);
}
Complex Complex::operator/(Complex&c2)
{
return Complex((real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag),(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag));
}