对象重载前置++和后置++运算符

#include 
using namespace std;
class people
{
public:
	people() {}
	people(int age) :age(age) {}
	//前置++:
	people operator++()
	{
		++(this->age);
		return *this;
	}
	//后置++:
	people operator++(int)
	{
		people temp = *this;
		(this->age)++;
		return temp;
	}
	void show() { cout << "age= " << age << endl; }
private:
	int age;
};

int main()
{
	people peo1(15);
	cout << "原始数据:" << endl;
	peo1.show();

	cout << endl << "后置++:" << endl;
	people peo3 = peo1++;	//也即是先将peo1的赋值给peo2,然后再执行++操作
	peo1.show();//16		
	peo3.show();//15

	cout << endl << "前置++:" << endl;
	people peo2 = ++peo1;
	peo1.show();//17			
	peo2.show();//17

	/*
		int i = 3;
		int j = i++;	//j:3,i:4
		int j = ++i;	//j:5,i:5
	*/

	return 0;
}

对象重载前置++和后置++运算符_第1张图片

你可能感兴趣的:(C++,c++,开发语言)