前置++后置++递增运算符重载

3.1 自己实现int类型 MyInteger
3.2 内部维护以int数据
3.3 MyInteger myInt
3.4 myInt ++ 后置 ++myInt 前置
3.5 重载++运算符 operator++() 前置 operator++(int) 后置
3.6 前置理念 先++ 后返回自身 后置理念 先保存住原有值 内部++ 返回临时数据

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>

using namespace std;

#if(1)
class Nick {
public:
	//friend ostream& operator<<(ostream &cout, Nick &nick);
	friend ostream& operator<<(ostream &cout, Nick nick);
	Nick(int val) :m_val(val) {};
	Nick() {
		m_val = 0;
	}

	//前置++重载
	Nick& operator++() {
		this->m_val++;
		return *this;
	}

	//后置++重载
	Nick operator++(int) {
		//先保存目前数据
		Nick temp = *this;
		m_val++;
		return temp;
	}

private:
	int m_val;
};
ostream& operator<<(ostream &cout, Nick nick)
//ostream& operator<<(ostream &cout, Nick &nick) 
{
	cout << nick.m_val;
	return	cout;
}

void test01() {
	Nick nick1(32);
	Nick nick2;

	cout << "++nick1 = " << ++nick1 << endl;
	cout << "nick2++ = " << nick2++ << endl;//报错:二进制“<<”: 没有找到接受“MyInteger”类型的右操作数的运算符(或没有可接受的转换)
	//C2679 binary '<<': no operator found which takes a right - hand operand of type 'MyInteger' (or there is no acceptable conversion)
	/*
	解决方法:
	1)后缀++返回的是值而不是引用,<<运算符的重载只接受引用类型的参数,因此要进行强制类型转换
	2)将<<运算符重载时第二个参数由引用改为值
	*/
	//cout << "nick2++ = " << (Nick&)nick2++ << endl;
	cout << "nick1 = " << nick1 << endl;
}
int main(){
	test01();

	system("pause");
	return 0;
}
#endif
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值