递减运算符重载

2023-12-26 21:26:19

//递减运算符重载和递增运算符重载原理相同,只是运算符不一样

前一篇就是递增运算符重载,不懂哥可以康康;

//递减运算符重载
#include<iostream>
using namespace std;
//递减运算符重载和递增运算符重载原理相同,只是运算符不一样
class MyInteage
{
	friend ostream& operator<<(ostream& cout,const MyInteage& myint);
public:
	MyInteage()
	{
		m_num = 3;
	}
	//前置递减运算符重载,函数声明并实现
	MyInteage& operator--()
	{
		//先--
		m_num--;
		//然后返回自身
		return *this;
	}
	MyInteage operator--(int)
	{
		//创建一个临时对象来保存当前的值
		MyInteage temp = *this;
		m_num--;
		return temp;
	}
private:
	int m_num;
};
ostream& operator<<(ostream& cout,const MyInteage& myint)
{
	cout << myint.m_num;
	return cout;
}

void test01()
{
	MyInteage myint;
	cout <<"--myint = " <<--myint<<endl;
	cout <<"myint = "<< myint<<endl;
}
void test02()
{
	MyInteage myint;
	cout << "myint-- = " << myint-- << endl;
	cout << "myint = " << myint << endl;
}
int main(void)
{
	//test01();
	test02();
	system("pause");
	return 0;
}

文章来源:https://blog.csdn.net/xms12_3/article/details/135230204
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。