编写程序声明Point类,在类中声明整型的私有成员变量x、y,声明成员函数Point& operator++( );Point operator++( int);以实现对Point类重载“++”(自增)运算符,声明成员函数Point& operator--( );Point operator--( int);以实现对Point类重载“--”(自减)运算符,实现对坐标值的改变。 在主函数中完成充分测试! 输入 输出 1 1 a的值为:1 , 1 after a++,a的值为:2 , 2 after ++a,a的值为:3 , 3 after a--,a的值为:2 , 2 after --a,a的值为:1 , 1
时间: 2024-02-21 20:00:24 浏览: 11
下面是实现了 Point 类并重载了 ++ 和 -- 运算符的代码:
```cpp
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int nx=0, int ny=0): x(nx), y(ny) {}
Point& operator++()
{
++x;
++y;
return *this;
}
Point operator++(int)
{
Point temp(*this);
++x;
++y;
return temp;
}
Point& operator--()
{
--x;
--y;
return *this;
}
Point operator--(int)
{
Point temp(*this);
--x;
--y;
return temp;
}
int getx() { return x; }
int gety() { return y; }
};
int main()
{
int m, n;
cin >> m >> n;
Point a(m, n);
cout << "a的值为:" << a.getx() << " , " << a.gety() << endl;
a++;
cout << "after a++,a的值为:" << a.getx() << " , " << a.gety() << endl;
++a;
cout << "after ++a,a的值为:" << a.getx() << " , " << a.gety() << endl;
a--;
cout << "after a--,a的值为:" << a.getx() << " , " << a.gety() << endl;
--a;
cout << "after --a,a的值为:" << a.getx() << " , " << a.gety() << endl;
return 0;
}
```
程序中实现了 Point 类,其中包含了两个私有成员变量 x 和 y,以及四个重载的运算符:++、--、后缀++和后缀--。其中 ++ 和 -- 运算符分别实现了前缀自增和前缀自减,而后缀++ 和后缀-- 运算符则实现了后缀自增和后缀自减。在每个运算符函数中,都对对象的坐标值进行了相应的改变,并返回改变后的对象。
在主函数中,首先输入了两个整数 m 和 n,然后通过构造函数 Point(int nx=0, int ny=0) 创建了一个 Point 对象 a,其坐标为 (m,n)。接下来先输出 a 的坐标,然后分别进行了 a++、++a、a--、--a 操作,并输出每一次操作后 a 的坐标。
最终输出结果为:
a的值为:1 , 1
after a++,a的值为:2 , 2
after ++a,a的值为:3 , 3
after a--,a的值为:2 , 2
after --a,a的值为:1 , 1
可以看到,运算符重载的效果符合预期,对象的坐标值在每次运算符操作后都发生了相应的改变。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)