友元类:把一个类作为另一个类的友元,如果一个类指定了友元类,则友元类的成员函数可以访问此类包括非公有成员在内的所有成员
友元的利弊:友元不是类成员,但是它可以访问类中的私有成员。友元的作用在于提高程序的运行效率,但是,它破坏了类的封装性和隐藏性,使得非成员函数可以访问类的私有成员。不过,类的访问权限确实在某些应用场合显得有些呆板,从而容忍了友元这一特别语法现象。
注意事项:
(1) 友元关系不能被继承
(2) 友元关系是单向的,不具有交换性。若类B是类A的友元,类A不一定是类B的友元,要看在类中是否有相应的声明。
(3) 友元关系不具有传递性。若类B是类A的友元,类C是B的友元,类C不一定是类A的友元,同样要看类中是否有相应的申明
#include "stdafx.h"
#include <iostream>
using namespace std;
#if 0
把PointManagement声明为Point的友元,Point的对象就可以
在PointManagement的类(或者函数)中访问Point的private数据成员
#endif
class Point
{
public:
Point(double xx, double yy)
:x(xx), y(yy) {}
friend class PointManagement; //声明为Point的友元类
private:
double x, y;
};
class PointManagement
{
public:
double getDirectDistance(Point &a, Point &b);
double getTriDistance(Point &a, Point &b);
};
double PointManagement::getDirectDistance(Point &a, Point &b)
{
double dx = a.x - b.x;
double dy = a.y - b.y;
return sqrt(dx*dx + dy*dy); //sqrt 为开平方的函数
}
int _tmain(int argc, _TCHAR* argv[])
{
Point a(1, 2); Point b(3, 4);
PointManagement pm;
double dis = pm.getDirectDistance(a, b);
cout << dis << endl;
return 0;
}