0
点赞
收藏
分享

微信扫一扫

自增,自减运算符的重载

暮晨夜雪 2022-02-27 阅读 55

一:前置运算符作为一元运算符重载:

1.重载为成员函数:

T & operator++();

T & operator--();

2.重载为全局函数:

T1 & operator++(T2);

T1 & operator--(T2);

二:后置运算符作为二元运算符重载,多写一个没用的参数:

1.重载为成员函数:

T & operator++(int);

T & operator--(int);

2.重载为全局函数:

T1 & operator++(T2,int);

T1 & operator--(T2,int);

#include<iostream>
using namespace std;
class Complex
{
	private:
		int n;
	public:
		Complex(int a=0):n(a){}
		operator int(){return n;}
		Complex& operator++();
		Complex operator++(int );
		friend Complex& operator--(Complex& );
		friend Complex operator--(Complex& ,int );
};
Complex& Complex::operator++()
{
	n++;
	return *this;
}
Complex Complex::operator++(int a)
{
	Complex temp=(*this);
	n++;
	return temp;
}
Complex& operator--(Complex& a)
{
	a.n--;
	return a;
}
Complex operator--(Complex& b,int a)
{
	Complex temp(b);
	b.n--;
	return temp;
}
int main()
{
	return 0;
}
举报

相关推荐

0 条评论