用C++运算符重载,实现点对象的+-运算 设计一个点类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(); }
时间: 2024-04-04 13:32:32 浏览: 95
以下是完整的代码:
#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){ // 重载+运算符
return Point(x+p.x, y+p.y);
}
Point operator-(const Point& p){ // 重载-运算符
return Point(x-p.x, y-p.y);
}
void setP(int x, int y){ // 设置点坐标
this->x = x;
this->y = y;
}
void show(){ // 显示点的坐标
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;
}
阅读全文
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20250102104920.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://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)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.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)