天天看點

C++運算符重載示例——複數

#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;
}