c++定义CPoint类,有两个成员变量:横坐标(x)和纵坐标(y),对CPoint类重载++(自增运算符)、--(自减运算符),实现对坐标值的改变。
时间: 2024-01-11 16:02:52 浏览: 232
可以使用如下代码来定义 CPoint 类,并实现自增、自减运算符的重载:
```c++
#include <iostream>
using namespace std;
class CPoint {
public:
CPoint(int x = 0, int y = 0) : x(x), y(y) {}
CPoint operator++() { // 前置自增运算符重载
++x;
++y;
return *this;
}
CPoint operator++(int) { // 后置自增运算符重载
CPoint tmp(*this);
++x;
++y;
return tmp;
}
CPoint operator--() { // 前置自减运算符重载
--x;
--y;
return *this;
}
CPoint operator--(int) { // 后置自减运算符重载
CPoint tmp(*this);
--x;
--y;
return tmp;
}
void print() {
cout << "(" << x << ", " << y << ")" << endl;
}
private:
int x, y;
};
int main() {
CPoint p(1, 2);
cout << "p = ";
p.print();
++p;
cout << "++p = ";
p.print();
p++;
cout << "p++ = ";
p.print();
--p;
cout << "--p = ";
p.print();
p--;
cout << "p-- = ";
p.print();
return 0;
}
```
输出结果为:
```
p = (1, 2)
++p = (2, 3)
p++ = (2, 3)
--p = (1, 2)
p-- = (1, 2)
```
阅读全文