c++自减运算符重载

c++自减运算符重载

网上看的视频学习的自加运算符重载后写的自减运算符重载,知道自加怎么写后再写自减非常好写。
本代码实现的功能是对一个类进行cout自减输出一个类内的参数,其中包含了左移运算符的重载。

需要注意的几个点

前置递减要返回引用,而后置递减返回的是值。这是因为如果后置递减返回引用那么返回的是一个局部对象的引用,当前函数执行完后局部对象会被释放 。

另外一些小技巧值得注意的是不可以用返回值作为函数重载的判断条件,有些时候可以加一个占位符来区分形参个数来添加函数重载。

示例代码

#include<iostream>
using namespace std;

class Myreducter
{
	
	friend ostream & operator<<(ostream &cout, Myreducter p);
public:
	Myreducter()
	{
		m_num = 10;
	}
	//前置减减
	Myreducter  & operator--()
	{
		m_num--;
		return *this;
	}
	//后置减减
	Myreducter operator--(int)
	{
		Myreducter temp = *this;
		m_num--;
		return temp;
	}

	//Myinteger operator++(int) {
	//	//先返回
	//	Myinteger temp = *this; //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
	//	m_num++;
	//	return temp;
	//}

private:
	int m_num;
};
ostream & operator<<(ostream &out, Myreducter p)
{
	out << p.m_num << endl;
	return out;
}



void test01()
{
	Myreducter pp;
	cout << (pp--) << endl;
	cout << pp << endl;

	Myreducter dd;
	cout << --dd << endl;
	cout << dd << endl;
}


int main()
{
	test01();
	system("pause");
	return 0;
}

输出为:
10

9

9

9

请按任意键继续. . .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值