它有2个私有成员x和y,表示点的坐标。另一个类为直线类Line,它有3个私有数据成员a,b和c,表示直线方程ax+by+c=0。这两个类中都说明了同一个友元函数dist,用于计算一个点到直线的距离。试在主函数中测试。
(这里需使用两个数学函数sqrt,fabs)
#include <iostream>
using namespace std;
…
class Point
{
…
};
class Line
{
…
};
…
int main()
{ Point O(0,0); //点;
Line L(1,1,-1); //直线;
double d; //距离
d=dist(O,L);
cout<<"点O到直线L的距离为:d="<<d<<endl;
return 0;
}
你可以参考一下,希望采纳
#include <iostream>
#include <math.h>
using namespace std;
class Point; //对类的引用性说明
class Line;
class Point
{
double x, y;
public:
Point(double x1, double y1) //定义构造函数
{
x = x1, y = y1;
}
friend double dist(Point&, Line&); //定义友元函数
};
class Line
{
double a, b, c;
public:
Line(double a1, double b1, double c1) //定义构造函数
{
a = a1, b = b1, c = c1;
}
friend double dist(Point&, Line&); //定义友元函数
};
//计算一个点到直线的距离
double dist(Point& P, Line& L)
{
double dis;
dis = fabs((L.a * P.x + L.b * P.y + L.c) / sqrt(L.a * L.a + L.b * L.b));
return dis;
}
int main()
{
Point O(0, 0); //点;
Line L(1, 1, -1); //直线;
double d; //距离
d = dist(O, L);
cout << "点O到直线L的距离为:d=" << d << endl;
return 0;
}
运行结果: