8-7对Point类重载++(自增)、--(自减)运算符,要求同时重载前缀和后缀的形式。
#include <iostream>
using namespace std;
class Point
{
public:
Point &operator ++();
Point operator++(int);
Point &operator --();
Point operator--(int);
Point() { ix = iy = 0; }
int x() { return ix; }
int y() { return iy; }
private:
int ix, iy;
};
Point& Point::operator++()
{
ix++;
iy++;
return *this;
}
Point Point::operator++(int)
{
Point temp = *this;
++*this;
return temp;
}
Point& Point::operator--()
{
ix--;
iy--;
return *this;
}
Point Point::operator--(int)
{
Point temp = *this;
--*this;
return temp;
}
int 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;
return 0;
}

本文介绍了一个C++示例程序,该程序通过定义Point类并重载++(自增)、--(自减)运算符来实现点坐标的更新。文章详细展示了如何为Point类重载前缀和后缀形式的自增与自减运算符,并提供了一个简单的测试案例。
3455

被折叠的 条评论
为什么被折叠?



