P212 成员函数和友元函数完成一元运算后置++和后置 - -

本文详细介绍了如何使用C++的成员函数和友元函数来实现一元运算符后置++和--的功能。通过实例代码解析了这两种操作符的重载方法,探讨了它们在类设计中的应用及其对封装性和效率的影响。
摘要由CSDN通过智能技术生成
#include <iostream>
using namespace std;

class Complex
{
	friend Complex& operator++(Complex &c1);
	friend Complex operator++(Complex &c1, int);
private:
	int a;
	int b;
public:
	Complex& operator--()
	{
		this->a--;
		this->b--;
		return *this;
	}
	Complex(int a = 0, int b = 0)
	{
		this->a = a;
		this->b = b;
	}
	void printCom()
	{
		cout << a << "+" << b << "i" << endl;
	}
	//成员函数 法 实现 - 运算符重载
	Complex operator-(Complex &c2)
	{
		Complex tmp(this->a - c2.a, this->b - c2.b);
		return tmp;
	}


	//后置--
	Complex operator--(int)
	{
		Complex tmp = *this;
		this->a--;
		this->b--;
		return tmp;

	}
};
Complex& operator++(Complex &c1)
{
	c1.a++;
	c1.b++;
	return c1;
}

Complex operator++(Complex &c1, int)
{
	Complex tmp = c1;

	//先使用,再++  即先把c1先返回去

	//return c1; //返回去&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值