#include <iostream>
using namespace std;
class Complex
{
public:
Complex(int real = 0, int image = 0) :real(real), image(image)
{
cout << this << " Complex()" << endl;
}
~Complex()
{
cout << this << " ~Complex()" << endl;
}
Complex(Complex &c) :real(c.real), image(c.image)
{
cout << this << " Complex(Complex &c)" << endl;
}
// + - 加减运算符重载
Complex operator+(const Complex &c)
{
cout << this << " Complex operator+(Complex c)" << endl;
return Complex(this->real + c.real, this->image + c.image);
}
Complex operator-(const Complex &c)
{
cout << this << " Complex operator-(Complex c)" << endl;
return Complex(this->real - c.real, this->image - c.image);
}
// << >> 插入和提取运算符重载
istream& operator>>(istream &i_s)
{
cout << this << " istream& operator>>(istream &i_s)" << endl;
i_s >> real >> image;
getchar();
return i_s;
}
ostream& operator<<(ostream &o_s)
{
cout << this << " ostream& operator<<(ostream &o_s)" << endl;
o_s << real;
if (image >= 0)
o_s << '+';
o_s << image << 'i';
return o_s;
}
// - 负号运算符重载
Complex operator-(void)
{
cout << this << " Complex operator-(void)" << endl;
return Complex(-real, -image);
}
// ++ -- 前置自增自减运算符重载
Complex& operator++(void)
{
cout << this << " Complex& operator++(void)" << endl;
++real;
++image;
return *this;
}
Complex& operator--(void)
{
cout << this << " Complex& operator--(void)" << endl;
--real;
--image;
return *this;
}
// ++ -- 前置自增自减运算符重载
Complex operator++(int)
{
cout << this << " Complex& operator++(int)" << endl;
Complex old(*this);
++real;
++image;
return old;
}
Complex operator--(int)
{
cout << this << " Complex& operator--(int)" << endl;
Complex old(*this);
--real;
--image;
return old;
}
void show(void)
{
cout << this << " void show(void) ";
cout << real;
if (image >= 0)
cout << '+';
cout << image << 'i' << endl;
}
private:
int real;
int image;
};
int main(void)
{
Complex c0(1, 2);
c0.show();
c0 = c0.operator+(c0);
c0.show();
c0 = c0 - c0;
c0.show();
Complex c1;
c1.operator>>(cin);
c1.operator<<(cout) << endl;
Complex c2;
c2.operator>>(cin);
c2.operator<<(cout) << endl;
Complex c3;
c3.operator>>(cin);
c3.operator<<(cout) << endl;
//c1 = -c1;
//c1.operator<<(cout) << endl;
//c2 = -(-c2);
//c2.operator<<(cout) << endl;
//c1 = --c3;
//c1.operator<<(cout) << endl;
//c3.operator<<(cout) << endl;
//c2 = ++c3;
//c2.operator<<(cout) << endl;
//c3.operator<<(cout) << endl;
c1 = c3--;
c1.operator<<(cout) << endl;
c3.operator<<(cout) << endl;
c2 = c3++;
c2.operator<<(cout) << endl;
c3.operator<<(cout) << endl;
return 0;
}