1. C++题目62:运算符重载,实现点对象的+-运算 设计一个点类Point,实现点对象之间的+和-运算。 #include<iostream> using namespace std; 提供补充代码 int main() { Point p1,p2,psum,psub; int x,y; cin>>x>>y; p1.setP(x,y); cin>>x>>y; p2.setP(x,y); psum=p1+p2; psub=p1-p2; cout<<"两点相加:"; psum.show(); cout<<"两点相减:"; psub.show(); } 【输入形式】 两个点坐标 【输出形式】 两个点相加及相减的结果 【样例输入】 2 3 2 4 【样例输出】 两点相加:[4,7] 两点相减:[0,-1]
时间: 2024-03-20 16:43:10 浏览: 91
以下是完整的代码实现:
```cpp
#include<iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int _x = 0, int _y = 0) : x(_x), y(_y) {}
Point operator+(const Point &p) const {
return Point(x + p.x, y + p.y);
}
Point operator-(const Point &p) const {
return Point(x - p.x, y - p.y);
}
void setP(int _x, int _y) {
x = _x;
y = _y;
}
void show() const {
cout << "[" << x << "," << y << "]" << endl;
}
};
int main() {
Point p1, p2, psum, psub;
int x, y;
cin >> x >> y;
p1.setP(x, y);
cin >> x >> y;
p2.setP(x, y);
psum = p1 + p2;
psub = p1 - p2;
cout << "两点相加:";
psum.show();
cout << "两点相减:";
psub.show();
return 0;
}
```
运算符重载的实现可以使用成员函数或者非成员函数,这里我们使用成员函数来实现。在Point类中,我们重载了+和-运算符,实现了点对象的加减运算。setP函数用于设置点的坐标,show函数用于输出点的坐标。在主函数中,我们利用输入来设置两个点的坐标,然后进行加减运算并输出结果。
输入样例:
```
2 3
2 4
```
输出样例:
```
两点相加:[4,7]
两点相减:[0,-1]
```
阅读全文
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)