您好,欢迎来到保捱科技网。
搜索
您的当前位置:首页重载自增,自减运算符

重载自增,自减运算符

来源:保捱科技网

class operator++();用于重载先加一(减一)然后运算的情况

class operator++(int);用于重载先运算,然后加一(减一)的情况

系统会根据是++class 还是 class ++来进行判断使用那一个重载函数,重载函数中的内容需要用户自己进行定义

例子一:

#include<iostream>
using namespace std;
class Counter 
{
	public:
		Counter()
		{
			v = 0;
		} 
		Counter operator ++();
		Counter operator ++(int);
		int v;
};
Counter Counter::operator ++()
{
	v++;
	return *this;
}
Counter Counter::operator ++(int)
{
	Counter t;
	t.v = v++;
	return t;
} 
int main()
{
	Counter c;
	cout<<"c.v++:"<<c.v++<<endl;
	cout<<"++c.v:"<<++c.v<<endl;
} 


例子二:

#include<iostream>
using namespace std;
class counter
{
	public:
		counter()
		{
			v = 0;
		}
		counter operator ++();
		counter operator ++(int);
		void print()
		{
			cout<<v<<endl;
		}
	private:
		unsigned v;
};
counter counter::operator ++()
{
	v++;
	return *this;
}
counter counter::operator ++(int)
{
	counter temp(*this);
	v++;
	return temp;
}
int main()
{
	counter c;
	for(int i=0;i<8;i++)
	{
		c++;
	}
	c.print();
	for(int i=0;i<8;i++)
	{
		++c;
	}
	c.print();
	return 0;
}


转载于:https://www.cnblogs.com/zhezh/p/3773352.html

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baoaiwan.cn 版权所有 赣ICP备2024042794号-3

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务