實驗7.1 對Point類重載“++”(自增)、“–”(自減)運算符

題目

定義Point類,有座標_x,_y兩個成員變量;對Point類重載“++”(自增)、“–”(自減)運算符,實現對座標值的改變。

C++代碼如下:

#include<iostream>
using namespace std;

class Point
{
private:
	int x,y;
public:
	Point(int a,int b){x=a,y=b;}
	Point& operator++();
	Point operator++(int);
	Point& operator--();
	Point operator--(int);
	void showPoint();
}; 

Point & Point::operator++()//前置++ 
{
	++x,++y;
	return *this;
}
Point Point::operator++(int)//後置++ 
{
	x++,y++;
	return *this;
}
Point & Point::operator--()//前置-- 
{	
	--x,--y;
	return *this;
}
Point Point::operator--(int)//後置--
{
	x--,y--;
	return *this;
} 
void Point::showPoint()
{
	cout<<"x="<<x<<"  y="<<y<<endl;
}

int main()
{
	Point p(2,3);
	p.showPoint();
	cout << "前置++:";
	++p;
	p.showPoint();
	cout << "後置++:" ;
	p++;
	p.showPoint();
	cout << "前置--:" ;
	--p;
	p.showPoint();
	cout << "後置--:" ;
	p--;
	p.showPoint();
	return 0;
}

運行結果:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章