C++中的运算符重载(二)——自增自减运算符重载

概述:
对于常用到的自增(++),自减(- -)运算符来说,稍微比左移运算符要复杂一些,以为自增和自减运算符包括前置和后置(就是所说的++在前或者++在后)

如下:一个简单的自增运算符代码

#include <iostream>
#include <string>

using namespace std;
/**/
class Myint {
public:
	Myint(int num)
	{
		this->num = num;
	}
	Myint& operator++()
	{
		this->num = this->num + 1;
		return *this;
	}
	Myint operator++(int)
	{
		Myint temp = *this;
		this->num = this->num + 1;
		return temp;
	}
	int num;
};

ostream& operator<< (ostream &cout, Myint& p)
{
	cout << p.num ;

	return cout;
}


void test01()
{
	Myint p1(10);
	Myint p(0);
	cout << p1 << endl;/*operator++(p1),*/
	++p1;
	cout << ++p1 << endl;
	p = p1++ ;
	cout << p << endl;
	cout << p1 << endl;
}
int main()
{
	test01();

	return 0;
}

注意:
(++)在前的时候和在后的时候需要的重载运算符函数不一样,重载运算符函数有两种形式,全局重载和类内重载
全局重载

Myint& operator++(Myint& p)
Myint operator++(Myint& p,int)
/*后面函数(++在后)重载的时候需要占位参数,而且必须要写在后面*/

类内重载

Myint& operator++()
Myint operator++(int)
/*需要有占位参数*/

返回参数
对于++p来说,就是直接加一返回,由于不需要保存上次的值所以直接返回引用就可以
对于p++来说,由于要保存上次的值,也就是创建个临时对象,来保存上次对象的状态,再加一,最后返回临时对象的值。
自减运算符简单代码;

#include <iostream>
#include <string>

using namespace std;
/**/
class Myint {
public:
	Myint(int num)
	{
		this->num = num;
	}
	Myint& operator--()
	{
		this->num = this->num + 1;
		return *this;
	}
	
	int num;
};
Myint operator--(Myint& p,int)
{
	Myint temp = p;
	p.num = p.num + 1;
	return temp;
}
ostream& operator<< (ostream &cout, Myint& p)
{
	cout << p.num ;

	return cout;
}


void test01()
{
	Myint p1(10);
	Myint p(0);
	cout << p1 << endl;/*operator--(p1),*/
	--p1;
	cout << --p1 << endl;
	p = p1-- ;
	cout << p << endl;
	cout << p1 << endl;
}
int main()
{
	test01();

	return 0;
}

注:自减运算符和自增运算符一样,都可以类内实现和全局实现
总结:
优先使用++和–的标准形式,优先调用前置++。 如果定义了++c,也要定义 c++, 递增操作符比较麻烦,因为他们都有前缀和后缀形式,而两种语义略有不同。重载 operator++和 operator–时应该模仿他们对应的内置操作符。 对于++和–而言,后 置形式是先返回,然后对象++或者–,返回的是对象的原值。前置形式,对象先++ 或–,返回当前对象,返回的是新对象。其标准形式为:
在这里插入图片描述
调用代码时候,要优先使用前缀形式,除非确实需要后缀形式返回的原值,前缀和 后缀形式语义上是等价的,输入工作量也相当,只是效率经常会略高一些,由于前 缀形式少创建了一个临时对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值