123 递增运动算符重载

#include<iostream>
using namespace std;
//递增运算符重载
//int a=10;cout<<a++<<endl;->10   ;cout<<a<<endl; ->11;
//int b=10;cout<<++b<<endl;->11;cout<<b<<endl;->11;
//
class MyInteger
{
	friend ostream& operator<<(ostream& cout, MyInteger myint);
public:
	MyInteger()//在构造函数中初始化成员
	{
		m_num = 0;
	}
	//重载前置++运算符
	MyInteger operator++()//返回引用时为了一直对一个数据进行操作
	{
		m_num++;
		return *this;//this是指向自身的指针,*this就是解引用自身
	}
	//重载后置++运算符

private:
	int m_num;

};
//重载左移运算符<<:为了左移运算符在左边,所以重载要要在全局函数中
ostream& operator<<(ostream& cout, MyInteger myint)
{
	cout << myint.m_num;
	return cout;
}

void test01()
{
	MyInteger myint;
	cout <<++ (++myint) << endl;
	cout << myint << endl;
}



int main()
{
	test01();



	system("pause");
	return 0;
}

在这里插入图片描述
在这里插入图片描述

#include<iostream>
using namespace std;
//递增运算符重载
//int a=10;cout<<a++<<endl;->10   ;cout<<a<<endl; ->11;
//int b=10;cout<<++b<<endl;->11;cout<<b<<endl;->11;
//
class MyInteger
{
	friend ostream& operator<<(ostream& cout, MyInteger myint);
public:
	MyInteger()//在构造函数中初始化成员
	{
		m_num = 0;
	}
	//重载前置++运算符
	MyInteger& operator++()//返回引用时为了一直对一个数据进行操作
	{
		//先进行++操作
		m_num++;
		//后返回自身
		return *this;//this是指向自身的指针,*this就是解引用自身
	}
	//重载后置++运算符
	MyInteger operator++(int)//这里的int时占位参数,可以区分前置和后置递增
	{//不能返回temp的引用,因为tmp是一个局部数据,局部对象在当前数据执行完后就被释放掉了,如果还要返回引用就是非法操作了
	
		//先返回自身  ->记录自身及结果
		MyInteger temp = *this;
		//后进行++操作
		m_num++;
		//将记录的结果返回
		return temp;
	}

private:
	int m_num;

};
//重载左移运算符<<:为了左移运算符在左边,所以重载要要在全局函数中
ostream& operator<<(ostream& cout, MyInteger myint)
{
	cout << myint.m_num;
	return cout;
}

void test01()
{
	MyInteger myint;
	cout <<++ (++myint) << endl;
	cout << myint << endl;
	

}

void test02()
{
	MyInteger myint;
	cout << myint++ << endl;
	cout << myint << endl;


}


int main()
{
	test01();
	test02();



	system("pause");
	return 0;
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

磁生电

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

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

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

打赏作者

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

抵扣说明:

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

余额充值