友元函数
1、友元函数是在类声明中由关键字friend修饰说明 的非成员函数,在它的函数体中能够通过对象名访 问 private 和 protected成员
2、作用:增加灵活性,使程序员可以在封装和快速性 方面做合理选择。
3、访问对象中的成员必须通过对象名。
友元函数举例说明:
#include "iostream"
#include "cmath"
using namespace std;
//定义一个point类
class Point
{
public:
Point(float x=0,float y=0):x(x),y(y){} //缺省的构造函数,该函数可以表示缺省的情况,也可以表示带参数的情况
//Point(int newx,int newy):x(newx),y(newy){}; //含参数的构造函数
Point(const Point & p); //复制构造函数
~Point(){ };
//以下为成员函数
friend float dis_F(const Point A ,const Point B); //通过友元函数进行计算两点距离
float dis(const Point B); //通过成员函数计算两点距离
private:
float x,y;
};
Point::Point(const Point & p)
{
x =p.x;
y = p.y;
}
float dis_F(const Point A ,const Point B) //友元函数
{
float disAB = sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
return disAB;
}
float Point::dis(const Point B)
{
double xx = (B.x - x)*(B.x - x);
double yy = (B.y - y)*(B.y - y);
return sqrt(xx+yy);
}
int main(int argc,char *argv[])
{
Point p1(1,1.3),p2(4,5);
cout << "[Friend Function]The distance is:"<<dis_F(p1,p2) <<endl; //通过友元函数计算
cout << "[ClassMember Function]The distance is:"<<p1.dis(p2); //通过成员函数计算
return 0;
}
运行结果:
友元类
友元关系是单向的 如果声明B类是A类的友元,B类的成员函数就 可以访问A类的私有和保护数据,但A类的成员函 数却丌能访问B类的私有、保护数据。