写一个点类,将横、纵坐标作为其私有数据成员,定义带两个参数(横、纵坐标)的构造函数,对横、纵坐标进行初始化,编写程序求两点之间的距离,要求用友元函数(考虑一下不用友元函数如何解决)。
代码1:
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
double x;
double y;
friend double Dis(Point &a,Point &b);
public:
void print()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
Point(double a,double b):x(a),y(b) {}
};
double Dis(Point &a,Point &b)
{
double x;
x=a.x - b.x;
double y;
y=a.y - b.y;
return sqrt(x*x+y*y);
}
int main()
{
Point pa(3,4),pb(6,8);
cout<<"两个点的坐标是:\n";
pa.print();
pb.print();
cout<<"两个点之间的距离是:";
cout<<Dis(pa,pb)<<endl;
}
代码2:
#include<iostream>
#include<cmath>
using namespace std;
class point {
private:
int x;
int y;
public:
friend double dis(point x, point y);
point(int x1, int y1) {
x = x1;
y = y1;
cout <<"("<< x <<","<< y<<")"<<endl;
}
};
double dis(point r1, point r2) {
int reselt;
reselt = ((r2.x - r1.x) * (r2.x - r1.x))+(r2.y - r1.y) * (r2.y - r1.y);
reselt = sqrt(reselt);
return reselt;
}
int main() {
cout << "两个点的坐标是:\n";
point A(3,4);
point B(6,8);
cout << "两个点之间的距离是:" << dis(A, B) << endl;
return 0;
}
运行结果: