C++ 运算符重载(复数类为例)

/* 运算符重载(复数为例),两种重载形式:重载为类的非静态函数(加法),重载为非成员函数(减法)
 * 实现 +,-,++,--,<< 运算符的重载
 * date: Mar,27
**/
#include 
#include 

using namespace std;

class Complex	// 复数类
{
	public:
		Complex(double a, double b = 0.0):real(a), imag(b) {}

		Complex operator+ (const Complex c)	// 重载 +
		{
			double r = real + c.real;
			double v = imag + c.imag;
			return Complex(r, v);
		}

		Complex operator++()	// 重载前置++,没有形参
		{
			real++;
			return *this;
		}

		Complex operator++(int)	// 重载后置++,有 int 形参
		{
			Complex old = *this;	// 调用 this
			++(*this);	// 调用前置++
			return old;
		}

		friend Complex operator-(const Complex c1, const Complex c2);	// - 重载为非成员函数
		friend Complex operator--(Complex &c);	// 重载前置--
		friend Complex operator--(Complex &c, int);	// 重载后置--
		friend ostream &operator<<(ostream &out, const Complex c);	// 重载 <<,只能重载为非成员函数

		void print()
		{
			if (fabs(imag - 0.0) < 10e-6)
				cout << real << endl;
			else if (imag > 0)
				cout << real << "+" << imag << "i" << endl;
			else
				cout << real << imag << "i" << endl;
		}

	private:
		double real;
		double imag;
};

Complex operator-(const Complex c1, const Complex c2)
{
	double r = c1.real - c2.real;
	double v = c1.imag - c2.imag;
	return Complex(r, v);	// 临时对象语法
}

Complex operator--(Complex &c)
{
	c.real--;
	return c;
}

Complex operator--(Complex &c, int)	//
{
	Complex old = c;
	c.real--;
	return old;
}

ostream &operator<<(ostream &out, const Complex c)
{
	if (fabs(c.imag - 0.0) < 10e-6)	// 虚部为 0 时,直接输出实部
		cout << c.real;
	else if (c.imag > 0)
		cout << c.real << "+" << c.imag << "i";
	else
		cout << c.real << c.imag << "i";
}

int main(void)
{
	Complex c1(0, -1.1);
	Complex c2(2.6);
	Complex c3 = c1 + c2;
	Complex c4 = c1 - c2;

	(c3--).print();
	cout << --c4 << endl;
	
	return 0;
}

需注意的点:

  • 对于+-++--,它们既可以重载为类的成员函数,也可以重载为非成员函数
  • 对于++--而言,它们又分为前置和后置两种情况,重载为前置时函数是不带形参的,但重载为后置时需要带一个 int 形参;问我为什么,那就是 老鳖的屁股—规定;且对于函数参数表中未使用到的参数,C++ 允许不给出参数名
  • <<只能重载为非成员函数

你可能感兴趣的:(C++)