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

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

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++ 允许不给出参数名
  • <<只能重载为非成员函数
  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值