首页 > 试题广场 >

对 Point 类重载++(自增)、--(自减)运算符

[问答题]

Point 类重载++(自增)、--(自减)运算符

推荐

解:

#include <iostream.h>
class Point
{
public:
Point& operator++();
Point operator++(int);
Point& operator--();
Point operator--(int);
Point() { _x = _y = 0; }
int x() { return _x; }
int y() { return _y; }
private:
int _x, _y;
};
Point& Point::operator++()
{
_x++;
_y++;
return *this;
}
Point Point::operator++(int)
{
Point temp = *this;
++*this;
return temp;
}
Point& Point::operator--()
{
_x--;
_y--;
return *this;
}
Point Point::operator--(int)
{
Point temp = *this;
--*this;
return temp;
}
void main()
{
Point A;
cout << "A 的值为:" << A.x() << " , " << A.y() << endl;
A++;
cout << "A 的值为:" << A.x() << " , " << A.y() << endl;
++A;
cout << "A 的值为:" << A.x() << " , " << A.y() << endl;
A--;
cout << "A 的值为:" << A.x() << " , " << A.y() << endl;
--A;
cout << "A 的值为:" << A.x() << " , " << A.y() << endl;
}

程序运行输出:

A 的值为:0 , 0

A 的值为:1 , 1

A 的值为:2 , 2

A 的值为:1 , 1

A 的值为:0 , 0



发表于 2018-04-18 20:37:53 回复(0)