# day-03 类和对象--C++运算符重载--递增递减运算符重载

类和对象–C++运算符重载

C++ 预定义的运算符,只能用于基本数据类型的运算,不能用于对象的运算
如何使运算符能用于对象之间的运算呢

递增运算符重载

递增和递减一般是改变对象的状态,所以一般是重载为成员函数

1.前置递增

#include <iostream>
using namespace std;

class MyInteger{
	friend ostream& operator<<(ostream& out, MyInteger myint);//友元函数,使类外的可以访问私有属性

public:
	MyInteger(){
		m_Num = 0;
	}
	MyInteger& operator++(){//解引用
		m_Num++;//先++
		return *this;//再返回
	}

private:
	int m_Num;
};

ostream& operator<<(ostream& out, MyInteger myint) {
	out << myint.m_Num;
	return out;
}

void test() {//前置递增 先++ 再返回
	MyInteger myInt;
	cout << ++myInt << endl;
	cout << myInt << endl;
}

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

2.后置递增

#include <iostream>
using namespace std;

class MyInteger{
	friend ostream& operator<<(ostream& out, MyInteger myint);//友元函数,使类外的可以访问私有属性

public:
	MyInteger(){
		m_Num = 0;
	}


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

ostream& operator<<(ostream& out, MyInteger myint) {
	out << myint.m_Num;
	return out;
}

void test() {//后置++ 先返回 再++
	MyInteger myInt;
	cout << myInt++ << endl;
	cout << myInt << endl;
}

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

注意:

返回引用是为了始终对一个对象进行操作,保证链式编程思想

区分前置和后置用占位参数int,其他的不行
前置:MyInteger &operator++{ }
后置:MyInteger operator++(int) { }

后置递增不能使用引用的原因:使用完会被释放掉,不能返回局部地址,这是非法操作

递减运算符同理

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值