问题及代码:
/*
*copyright (c) 2016,烟台大学计算机学院
*All rights reserved.
*文件名称:hellow.cpp
*作者:田甜
*完成日期:2016年4月13日
*版本号:v1.0
*问题描述:用友员函数求两点间的距离
*输入描述:
*程序输出:按要求处理后输出
*/
#include <iostream>
#include <cmath>
using namespace std;
class CPoint
{
private:
double x;
double y;
public:
CPoint(double,double);
friend double get_far(CPoint &p1,CPoint &p2);//get_far为CPoint的友员函数
};
CPoint::CPoint(double xx,double yy):x(xx),y(yy){}
double get_far(CPoint &p1,CPoint &p2)
{
double far=sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
return far;
}
int main()
{
CPoint p1(0,0),p2(1,1);
cout<<get_far(p1,p2)<<endl;
return 0;
}
运行结果:
心得体会:
友员函数在类内声明,friend在前返回值类型在后,可以直接使用所引用的对象的private型数据