问题及代码:
/*烟台大学计算机与控制工程学院。
文件名称:友元函数用例
作者:马艳艳
完成日期:2016年4月11日
问题描述:;通过友元函数求距离;
输入描述:无
输出描述:输出距离
ps:本程序主要是老师为了让我们深刻理解友元函数概念及应用。
*/
#include <iostream>
#include<cmath>
using namespace std;
class Point
{
public:
Point (int x=0,int y=0):x(x),y(y){}
int getx()//据我所知这个在这是由于私有成员不能直接访问,所以只能在公共接口以类似t.getx()形式访问私有成员。
{
return x;
}
int gety()
{
return y;
}
friend float print2(Point const &p1,Point const &p2);//引用函数访问私有成员
private:
int x,y;
} ;
float print2(Point const &p1,Point const &p2)
{
double x=p1.x-p2.x;
double y=p1.y-p2.y;
return static_cast<float> (sqrt(x*x+y*y));
}
int main()
{
Point p1(1,1),p2(2,2);
cout<<"The distance is:";
cout<<print2(p1,p2)<<endl;
return 0;
}
运行结果: