c++ --------递减运算符重载

c++ --递减运算符重载

递减运算符重载原理其实和递增运算符重载相同,要了解原理可以去看我的递增运算符重载的文章,里面有递增运算符重载的注意事项和语法,这里只展示一下递减运算符的代码

#include<iostream>
#include<string>
using namespace std;

//递减运算符重载和递增运算符重载原理相同,只是运算符不一样
class Myint
{
public:
	friend ostream& operator<<(ostream& cout, Myint my);
	//前置递减运算符重载,函数声明
	Myint& operator--();
	Myint operator--(int);//同样需要使用占位参数来让编译器知道这是函数重载

	

public:
	int num = 2;
};

Myint& Myint::operator--()
{
	//自身先--
	num--;
	//然后返回自身
	return *this;
}


Myint Myint::operator--(int)
{
	//先创建一个临时对象来保存当前的值
	Myint temp = *this;
	num--;
	return temp;
}

ostream& operator<<(ostream& cout, Myint my)//由于后置递减运算符返回的是值,所以左移运算符传入对象时,不使用引用
{
	cout << "num的当前数值为:"<<my.num << endl;
	return cout;
}


void test01()
{
	Myint my;
	cout << "前置递减运算符重载" << endl;
	cout <<"前置递减"  <<(--my) << endl;
	cout <<"前置递减后my"  <<my << endl;

}
void test02()
{
	Myint my;
	cout << "后置递减运算符重载" << endl;
	cout << "后置递减前" << my << endl;
	cout << (my--) << endl;
	cout << "后置递减后" << my << endl;
}
int main()
{
	test01();
	test02();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值