C++ 重载 +、++、+= 运算符

运算符重载:给运算符赋予新的运算规则,如可以实现对象之间的运算。

以复数运算符为例,重载 +、前置++、后置++、+= 运算符:

class CComplex {
public:
	CComplex(int r = 0, int i = 0):real_(r),image_(i) { }  // 构造函数
	
	void show() {
		cout << this->real_ << "+" << this->image_ << "i" << endl;
	}

	// 重载 + , 成员函数。 可将此重载注释,因为全局的重载也可匹配
	CComplex operator+(const CComplex& src) {   
		return CComplex(this->real_ + src.real_
			, this->image_ + src.image_);
	}

	// 重载 前置++, 不带参数
	CComplex& operator++() {
		this->real_ += 1;
		this->image_ += 1;
		return *this;  // *this不是局部对象,出了作用域*this对象仍然存在,因此返回引用。
	}

	// 重载 后置++, 带参数(C++规定带int参数的就是后置++,与int数据类型无关)
	CComplex operator++(int) {
		CComplex cp = *this;
		this->real_ += 1;
		this->image_ += 1;
		return cp;
		// return CComplex(real_++, image_++);  // 等价于上面
	}

	// 重载 +=
	void operator+=(const CComplex& src) {
		this->real_ += src.real_;
		this->image_ += src.real_;
	}

	friend CComplex operator+(const CComplex& lhs, const CComplex& rhs);
	
private:
	int real_; // 实部
	int image_; // 虚部
};

CComplex operator+(const CComplex& lhs, const CComplex& rhs) {
	return CComplex(lhs.real_ + rhs.real_, lhs.image_ + rhs.image_);
}

void test() {
	CComplex cp01(10, 20);
	CComplex cp02(30, 30);

	/*
	重载 +
	*/
	CComplex res01 = cp01 + cp02; // 等价于cp01.operator+(cp02);
	res01.show();

	// 首先找到构造函数将10转为CComplex对象,然后再相加
	CComplex res02 = cp01 + 10; 
	res02.show();

	// 调用全局 + 运算符重载
	CComplex res03 = 10 + cp01; 
	res03.show();

	/*
	重载 前置++ 与 后置++
	*/
	CComplex cp03(1, 1);
	CComplex cp04(1, 1);
	CComplex res04 = ++cp03;
	res04.show();

	CComplex res05 = cp04++;
	res05.show();  // 1+1i
	cp04.show();   // 2+2i

	/*
	重载 +=
	*/
	CComplex cp05(1, 1);
	CComplex cp06(2, 2);
	cp05 += cp06;
	cp05.show();
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伟大的马师兄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值