#include<iostream>
using namespace std;
class Point
{
public:
Point(int vx, int vy);
Point & operator++(); //前置自增重载为成员函数
friend Point & operator--(Point &p);//前置自减重载为友元函数
void Display();
private:
int x, y;
};
////////////////////////////////////////////////////
Point::Point(int vx=0, int vy=0) { x = vx; y = vy; }
/////////////////////////////////////////////////////
void Point::Display()
{
cout << "(" << x << ", " << y << ")" << endl;
}
/////////////////////////////////////////////////////////
Point & Point::operator++()//前置自增重载为成员函数
{
if (x < 640) x++; //不超过屏幕的横界
if (y < 480) y++; //不超过屏幕的竖界
return *this;
}
//////////////////////////////////////////////////
Point & operator--(Point &p)//前置自减重载为友元函数
{ //设置形参是因为:友元函数为普通函数,
//没有this指针,不能自动指向对象的相应的数据成员
if (p.x > 0) p.x--;
if (p.y > 0) p.y--;
return p;
}
////////////////////////////////////////////////
int main()
{
Point p1(10, 10), p2(150, 150);
cout << "输出对象的数据成员:p1 = ";
p1.Display();
++p1; //测试前置自增
cout << "输出前置自增后对象的数据成员:++p1 = ";
p1.Display();
cout << "输出对象的数据成员:p2 = ";
p2.Display();
--p2; //测试前置自减
cout << "输出前置自减后对象的数据成员:--p2 = ";
p2.Display();
//system("pause");
return 0;
}
前置自增和前置自减——运算符重载
最新推荐文章于 2025-06-05 16:20:16 发布