题目:

定义Point类,有坐标x,y两个成员变量,利用友元函数对Point类重载“++”运算符,实现对坐标值的改变。具体要求如下:

(1) 编写程序定义Point类,在类中定义整型的私有成员变量x,y;

(2) 在类中定义两个友元函数,分别重载前置++和后置++;

(3) 编写主函数测试。主函数如下,不能更改。

主函数如下:


int main()

{Point a(1,2);

a++;

a.print();

Point b;

b=++a;

b.print();

a.print();

return 0;

}

image-20210509213831431

参考

#include <iostream>
using namespace std;
class Point {
public:
Point(int X , int Y );
friend Point operator++(Point& p);
friend Point operator++(Point& p, int);
void print(void);
private:
int x;
int y;
};

Point::Point(int X=0, int Y=0) :x(X), y(Y) {}
Point operator++(Point& p) {
++p.x;
++p.y;
return p;
}
Point operator++(Point& p, int) {
Point P(p); //先将形参的值保存下
p.x++;
p.y++;
return P; //返回被保存的形参的值
}
void Point::print() {
cout << "(" << x << "," << y << ")" << endl;
}
int main() {
Point a(1, 2);
a++;
a.print();
Point b;
b = ++a;
b.print();
a.print();
return 0;
}

图片版:

code