定义一个描述平面中的点的类point,成员变量包括点的坐标位置x,y,并且都为私有变量,利用类的构造函数为对象置初值。定义友元函数计算两点间距离。
#include <iostream>
#include <math.h>
using namespace std;
class point
{
double x, y;
public: point(double a, double b) { x = a; y = b; }
friend double Distance(const point& p1, const point& p2);
};
double Distance(const point& p1, const point& p2)
{
return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
int main()
{
point p1(1,1), p2(2,2);
cout << Distance(p1, p2) << endl;
return 0;
}
http://ideone.com/avCjiq
通过在线编译
结果
1.41421