在C++领域流传着这样一句话,同类对象间无私处,异类对象间有友元。 我们都知道,采用类的机制后实现了数据的隐藏与封装,类的数据成员一般定义为私有成员,成员函数一般定义为公有的,依此提供类与外界间的通信接口。但是,有时需要定义一些函数,这 些函数不是类的一部分,但又需要频繁地访问类的数据成员,这时可以将这些函数定义为该函数的友元函数。 友元函数的形式
friend 类型 函数名(形式参数);除了友元函数外,还有友元类,两者统称为友元。友元的作用是提高了程序的运行效率(减少了类型检查和安全性检查等都需要时间开销),但却破坏了封装性和隐藏性。使得非成员函数可以访问类的私有成员。友元可以是一个函数,也可以是一个类,分别称之为友元函数和友元类。
友元函数定义在类外的普通函数,它不属于类,但需要在类中声明。声明时加关键字friend。一个函数可以是多个类的友元函数,只需要在各个类中分别声明。 1.全局函数作为友元函数的案列
#include <iostream> #include <cmath> using namespace std; class Point { public: Point(double xx, double yy) { x = xx; y = yy; } void Getxy(); friend double Distance(Point &a, Point &b); private: double x, y; }; void Point::Getxy() { cout << "(" << x << "," << y << ")" << endl; } double Distance(Point &a, Point &b) { double dx = a.x - b.x; double dy = a.y - b.y; return sqrt(dx*dx + dy*dy); } int main() { Point p1(3.0, 4.0), p2(6.0, 8.0); p1.Getxy(); p2.Getxy(); double d = Distance(p1, p2); cout << "distance is = " << d << endl; return 0; }2、类成员函数做友元函数
#include <iostream> #include <cmath> using namespace std; //前向声明,是?一种不完全型声明,即只需提供类名(无需提供类实现)即可。仅可用 //于声明指针和引用。 class Point; class ManagerPoint { public: double Distance(Point &a, Point &b); }; class Point { public: Point(double xx, double yy) { x = xx; y = yy; } void Getxy(); friend double ManagerPoint::Distance(Point &a, Point &b); private: double x, y; }; void Point::Getxy() { cout << "(" << x << "," << y << ")" << endl; } double ManagerPoint::Distance(Point &a, Point &b) { double dx = a.x - b.x; double dy = a.y - b.y; return sqrt(dx*dx + dy*dy); } int main() { Point p1(3.0, 4.0), p2(6.0, 8.0); p1.Getxy(); p2.Getxy(); ManagerPoint mp; double d = mp.Distance(p1, p2); cout << "mp.Distance is = " << d << endl; return 0; }3、友元对象 友元类的所有成员函数都是另一个类的友元函数,都可以访问另一个类中 的隐藏信息(包括私有成员和保护成员)。当希望一个类可以存取另一个类的私有成员时,可以将该类声明为另一类的友元类。定义友元类的语句格式如下
friend class 类名例如
class A { public: friend class B; };测试案例:
#include <iostream> #include <cmath> using namespace std; class A { public: A(int xx, int yy) { x = xx; y = yy; } inline void test() { } private: int x, y; friend class B; }; class B { public: inline void Test() { A a(10, 20); cout << "x=" << a.x << "y=" << a.y << endl; } }; int main() { B b; b.Test(); return 0; }输出结果:
1、声明位置 友元声明以关键字 friend 开始,它只能出现在类定义中。因为友元不是授 权类的 成员,所以它不受其所在类的声明区域 public private和protected 的影响。通常我们 选择把所有友元声明组织在一起并放在类头之后。
2、友元的利弊 友元不是类成员,但是它可以访问类中的私有成员。友元的作用在于提高 程序的运 行效率,但是,它破坏了类的封装性和隐藏性,使得非成员函数可以访问类的私有成员。
3、使用友元注意事项 * 友元关系不能被继承。 * 友元关系是单向的,不具有交换性。若类 B 是类 A 的友元,类 A 不一定是类B 的友元,要看在类中是否有相应的声明。 * 友元关系不具有传递性。若类 B 是类 A 的友元,类 C 是 B 的友元,类 C 不一定 是类 A 的友元,同样要看类中是否有相应的声明。