C++重载操作符自增自减

#include <iostream>
using namespace std;

class Test 
{
	friend ostream& operator<<(ostream& os, const Test& t);
public:
	Test(int i) : m_i(i){}

	// 前缀++()
	Test& operator++()
	{
		++(this->m_i);
		return *this;
	}

	// 后缀()++
	const Test operator++(int)
	{
		Test temp = *this;
		++(*this);
		return temp;
	}

	// 前缀--()
	Test& operator--()
	{
		--(this->m_i);
		return *this;
	}

	// 后缀()--
	const Test operator--(int)
	{
		Test temp = *this;
		--(*this);
		return temp;
	}

	int& operator*() const
	{
		return (int&)m_i;
	}
private:
	int m_i;
};

ostream& operator<<(ostream& os, const Test& t)
{
	os << "[" << t.m_i << "]";
	return os;
}

int main()
{
	Test t(5);
	cout << t++ << endl;
	cout << ++t << endl;
	cout << t-- << endl;
	cout << --t << endl;
	cout << *t << endl;
	system("pause");
	return 0;
}

 

posted @ 2019-03-05 01:55  jadeshu  阅读(179)  评论(0编辑  收藏  举报