设计一个点类(Point),具有数据成员x,y(点的坐标),以及设置、输出数据成员及求两点之间距离的功能。再编写主函数对该类进行测试。
时间: 2024-03-23 10:43:36 浏览: 121
好的,以下是Point类的实现代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
double x; // x坐标
double y; // y坐标
public:
Point(double x = 0, double y = 0) {
this->x = x;
this->y = y;
}
void setX(double x) {
this->x = x;
}
void setY(double y) {
this->y = y;
}
double getX() const {
return x;
}
double getY() const {
return y;
}
void print() const {
cout << "(" << x << "," << y << ")" << endl;
}
double distanceTo(const Point& p) const {
double dx = x - p.x;
double dy = y - p.y;
return sqrt(dx * dx + dy * dy);
}
};
int main() {
Point p1(1, 2);
Point p2(4, 6);
cout << "p1 = ";
p1.print();
cout << "p2 = ";
p2.print();
cout << "distance between p1 and p2 = " << p1.distanceTo(p2) << endl;
return 0;
}
```
在主函数中,我们创建了两个Point对象p1和p2,分别表示点(1,2)和(4,6)。在输出时,我们使用了成员函数print,将点的坐标以(x,y)的形式输出。在计算两点之间的距离时,我们使用了成员函数distanceTo,该函数接受一个常引用参数p,表示另一个点,返回值为两点之间的距离。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)