#include <iostream.h>
//using namespace std;
class complex{
protected:
int real,imag;
public:
complex(int a=0, int b=0)
{
real = a;
imag = b;
}
void display()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
friend complex operator+(complex& a, complex& b);
friend complex operator-(complex& a, complex& b);
friend complex operator*(complex& a, complex& b);
friend complex operator/(complex& a, complex& b);
friend complex operator++(complex &);
friend complex operator++(complex &,int);
complex operator=(complex &a); //=不能用友元重载
};
complex operator+(complex& a, complex& b)
{
complex c;
c.real = a.real + b.real;
c.imag = a.imag + b.imag;
return c;
}
complex operator -(complex& a, complex& b)
{
complex c;
c.real = a.real - b.real;
c.imag = a.imag - b.imag;
return c;
}
complex operator *(complex& a, complex& b)
{
complex c;
c.real = a.real * b.real - a.imag * b.imag;
c.imag = a.real * b.imag + a.imag * b.real;
return c;
}
complex operator /(complex& a, complex& b)
{
complex c;
c.real = (a.real * b.real + a.imag * b.imag) / (a.imag * a.imag +
b.imag * b.imag);
c.imag = (a.imag * b.real - a.real * b.imag) / (a.imag * a.imag +
b.imag * b.imag);
return c;
}
complex operator++(complex & a,int) //++n,编译器自动识别的,对于第二个参数是int,就是++n
{
complex c;
c.real = ++a.real;
c.imag = ++a.imag;
return c;
}
complex operator++(complex & a)//n++,编译器自动识别的,对于第二个参数没有,就是n++,跟里面的具体实现无关。若这个函数没写,则不管是n++,还是++n,都用上面那个++函数实现,但是会出现警告。
{
complex c;
c.real = a.real;
c.imag = a.imag;
a.real++;
a.imag++;
return c;
}
complex complex::operator=(complex &a)
{
real = a.real;
imag = a.imag;
return *this;
}
void main()
{
complex one(3,4), two(1,2), three;
three = one + two;
three.display();
three = one - two;
three.display();
three = one * two;
three.display();
three = one / two;
three.display();
one++;
one.display();
one++;
one.display();
three = one;
three.display();
complex four;
four = one++;
four.display();
one.display();
++one;
one.display();
four = ++one;
four.display();
}