首页 > 技术文章 > 重载自增,自减运算符

zhezh 2014-01-03 00:42 原文

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;
}


推荐阅读