重载操作符

STL中重载++,--操作符

#include<iostream>
using namespace std;

class INT
{
	friend ostream& operator<<(ostream& os, const INT& i);

public:
	INT(int x) :m_i(x) {};

	INT& operator++()
	{
		++(this->m_i);
		return *this;
	}

	INT operator++(int)
	{
		INT temp = *this;
		++(*this);
		return temp;
	}


	INT& operator--()
	{
		--(this->m_i);
		return *this;
	}


	INT operator--(int)
	{
		INT temp = *this;
		--(*this);
		return temp;
	}

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


private:
	int m_i;

};

ostream& operator<<(ostream& os, const INT& i)
{
	os << i.m_i;
	return os;
}


int main()
{
	INT I(5);
	cout << I++ << endl;
	cout << ++I << endl;
	cout << I-- << endl;
	cout << --I << endl;
	cout << *I<< endl;

}
注意:前置返回引用,后置返回临时变量(不能是引用)

猜你喜欢

转载自blog.csdn.net/alatebloomer/article/details/80526685
今日推荐