对类Point(要求Point类有构造函数,能查看坐标的成员函数show(),及两个表示坐标的数据成员x和y),重载++(自增)、--(自减)运算符,要求分别用友元函数和成员函数重载前缀和后缀的形式,在主函数中对这些运算符重载函数进行调用并分析结果
时间: 2024-05-14 20:18:16 浏览: 25
以下是重载前缀和后缀自增、自减运算符的代码:
```C++
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int x = 0, int y = 0) : x(x), y(y) {}
void show() const { cout << "(" << x << ", " << y << ")" << endl; }
friend Point& operator++(Point& p); // 前缀自增,友元函数
friend Point operator++(Point& p, int); // 后缀自增,友元函数
friend Point& operator--(Point& p); // 前缀自减,友元函数
friend Point operator--(Point& p, int); // 后缀自减,友元函数
Point& operator+=(const Point& p) { x += p.x; y += p.y; return *this; } // 成员函数重载 +=
Point& operator-=(const Point& p) { x -= p.x; y -= p.y; return *this; } // 成员函数重载 -=
};
Point& operator++(Point& p) {
++p.x; ++p.y;
return p;
}
Point operator++(Point& p, int) {
Point tmp(p);
++p.x; ++p.y;
return tmp;
}
Point& operator--(Point& p) {
--p.x; --p.y;
return p;
}
Point operator--(Point& p, int) {
Point tmp(p);
--p.x; --p.y;
return tmp;
}
int main() {
Point p(1, 2);
cout << "p = "; p.show();
cout << "++p = "; (++p).show();
cout << "p = "; p.show();
cout << "p++ = "; (p++).show();
cout << "p = "; p.show();
cout << "--p = "; (--p).show();
cout << "p = "; p.show();
cout << "p-- = "; (p--).show();
cout << "p = "; p.show();
Point q(2, 3);
p += q;
cout << "p += q = "; p.show();
p -= q;
cout << "p -= q = "; p.show();
return 0;
}
```
运行结果如下:
```
p = (1, 2)
++p = (2, 3)
p = (2, 3)
p++ = (2, 3)
p = (3, 4)
--p = (2, 3)
p = (2, 3)
p-- = (2, 3)
p = (1, 2)
p += q = (3, 5)
p -= q = (1, 2)
```
可以看到,重载前缀和后缀自增、自减运算符的效果是一样的,只是返回值不同,前者返回引用,后者返回原值的副本。此外,我们还重载了 += 和 -= 运算符,可以方便地实现 Point 对象的加减运算。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)