使用cpp语言设计并实现一个平面点类Point,要求(1)用x,y两个坐标值表示一个点(2)正确初始化每个点,默认坐标值为原点(3)计算点到原点的距离(4)计算到另一个点的距离(5)获取点x、y的坐标值(6)设置点x、y的坐标值(7)移动点到新的位置
时间: 2024-02-05 21:02:47 浏览: 151
这是一个技术问题。我可以回答你的问题。
以下是平面点类Point的cpp实现:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Point{
private:
double x;
double y;
public:
Point(){
x = y = 0;
}
Point(double a, double b){
x = a;
y = b;
}
double getDistance(){
return sqrt(x*x + y*y);
}
double getDistance(Point p){
double dx = x - p.x;
double dy = y - p.y;
return sqrt(dx*dx + dy*dy);
}
double getX(){
return x;
}
double getY(){
return y;
}
void setX(double px){
x = px;
}
void setY(double py){
y = py;
}
void move(double mx, double my){
x += mx;
y += my;
}
};
int main(){
Point p1, p2(3.0, 4.0);
cout << "The distance from the origin to p2 is: " << p2.getDistance() << endl;
cout << "The distance from p1 to p2 is: " << p1.getDistance(p2) << endl;
cout << "The x coordinate of p2 is: " << p2.getX() << endl;
cout << "The y coordinate of p2 is: " << p2.getY() << endl;
p2.setX(5.0);
p2.setY(6.0);
cout << "The new coordinates of p2 are: (" << p2.getX() << ", " << p2.getY() << ")" << endl;
p2.move(-2.0, 3.0);
cout << "The new coordinates of p2 after moving are: (" << p2.getX() << ", " << p2.getY() << ")" << endl;
return 0;
}
```
阅读全文