源程序:
#include<iostream>
#include<cmath>
using namespace std;
class CPoint
{
public:
CPoint(double xx=0,double yy=0):x(xx),y(yy){}
double distance1(CPoint &p);//成员函数的声明
friend double distance2(CPoint &, CPoint &);//友元函数的声明
double getx();//用于调出私有成员x
double gety();//用于调出私有成员y
private:
double x; // 横坐标
double y; // 纵坐标
};
double distance3(CPoint &p1, CPoint &p2);//一般函数的声明
double CPoint::distance1(CPoint &p)//成员函数的定义
{
return (sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y)));
}
double distance2(CPoint &p1, CPoint &p2)//友元函数的定义
{
return (sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)));
}
double distance3(CPoint &p1, CPoint &p2)//一般函数的定义
{
return (sqrt((p1.getx() - p2.getx()) * (p1.getx() - p2.getx()) + (p1.gety() - p2.gety()) * (p1.gety() - p2.gety())));
}
double CPoint::getx()
{
return x;
}
double CPoint::gety()
{
return y;
}
int main()
{
CPoint a(1, 0), b(3, 0);
cout << "利用成员函数输出距离:" << a.distance1(b) <<endl;
cout << "利用友元函数输出距离:" << distance2(a, b) <<endl;
cout << "利用一般函数输出距离:" << distance3(a, b) <<endl;
system("pause");
return 0;
截图:
这个程序与上次的程序差不太多~再加上贺老慈悲的发了个模板···照猫画虎做起来没有遇到太多困难···但是也遇到了一些问题···特别是粗心···一不小心将CPoint写成了CPiont···然后复制粘贴到了好几个地方···呵呵···好傻···必需细心才行啊···友元函数真的挺有意思哈~