设置点类point求两点之间距离,利用成员函数
时间: 2023-05-19 08:02:31 浏览: 52
可以使用以下代码实现:
```cpp
#include <iostream>
#include <cmath>
class Point {
public:
Point(double x, double y) : x_(x), y_(y) {}
double distanceTo(const Point& other) const {
double dx = x_ - other.x_;
double dy = y_ - other.y_;
return std::sqrt(dx * dx + dy * dy);
}
private:
double x_;
double y_;
};
int main() {
Point p1(0, 0);
Point p2(3, 4);
std::cout << "Distance between p1 and p2 is " << p1.distanceTo(p2) << std::endl;
return 0;
}
```
这个程序定义了一个点类 Point,其中包含了两个成员变量 x 和 y,表示点的坐标。类中还定义了一个成员函数 distanceTo,用于计算当前点与另一个点之间的距离。在主函数中,我们创建了两个点 p1 和 p2,并调用 p1 的 distanceTo 函数来计算两点之间的距离。
相关问题
c++ 实现一个简单的二维点类,用来求两点之间的距离
好的,以下是用 C++ 实现一个简单的二维点类,用来求两点之间的距离:
```cpp
#include <iostream>
#include <cmath>
class Point {
public:
Point(double x, double y) : x_(x), y_(y) {}
double distance(const Point& other) const {
double dx = x_ - other.x_;
double dy = y_ - other.y_;
return std::sqrt(dx * dx + dy * dy);
}
private:
double x_;
double y_;
};
int main() {
Point point1(0, 0);
Point point2(3, 4);
std::cout << point1.distance(point2) << std::endl; // 输出 5
return 0;
}
```
在上面的代码中,我们定义了一个 `Point` 类,其中包含两个私有成员变量 `x_` 和 `y_`,分别表示点的横、纵坐标。还有一个公有成员函数 `distance`,用来计算当前点和另一个点 `other` 之间的距离。
在 `distance` 函数中,我们先计算出两个点横坐标的差和纵坐标的差,然后利用勾股定理计算两点之间的距离。
使用时,先创建两个点的对象,然后调用其中一个点的 `distance` 方法,传入另一个点的对象即可,例如:
```cpp
Point point1(0, 0);
Point point2(3, 4);
std::cout << point1.distance(point2) << std::endl; // 输出 5
```
以上就是用 C++ 实现一个简单的二维点类,用来求两点之间的距离的方法。
设计一个程序,利用友元函数计算上题中平面上两点之间的距离
好的,我可以为你设计一个求平面上两点距离的程序,利用友元函数实现。以下是示例代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
double x, y;
public:
Point(double a = 0, double b = 0) : x(a), y(b) {}
friend double distance(Point p1, Point p2);
};
double distance(Point p1, Point p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return sqrt(dx*dx + dy*dy);
}
int main() {
Point p1(0, 0);
Point p2(3, 4);
cout << "Distance between (" << p1.x << "," << p1.y << ") and (" << p2.x << "," << p2.y << ") is " << distance(p1, p2) << endl;
return 0;
}
```
在上述程序中,我们定义了一个 `Point` 类,其中包含了两个私有变量 `x` 和 `y` 表示点的坐标。我们利用 `friend` 关键字声明了一个友元函数 `distance`,用于计算两个点之间的距离。在 `main` 函数中,我们创建了两个 `Point` 类型的对象 `p1` 和 `p2`,并且调用了 `distance` 函数,输出了两点之间的距离。
注意,在 `distance` 函数中,我们可以访问 `Point` 类的私有成员变量 `x` 和 `y`,因为我们已经在 `Point` 类中声明了 `distance` 函数是 `Point` 类的友元函数。这样,我们就可以通过友元函数计算平面上两点之间的距离了。