在 c + + 中什么时候应该使用‘ friend’ ?

类的友元函数在类的作用域之外定义,但它有权访问该类的所有私有和受保护成员。即使友元函数的原型出现在类定义中,但友元不是成员函数。

友元可以是函数、函数模板或成员函数,也可以是类或类模板,在这种情况下,整个类及其所有成员都是朋友。

要将函数声明为类的友元,请在类定义中的函数原型之前添加关键字friend,如下所示:

class Box {
   double width;
   public:
   double length;
   friend void printWidth( Box box );
   void setWidth( double wid );
};

要将类ClassTwo的所有成员函数声明为类ClassOne的好友,请将以下声明放入类ClassOne的定义中

示例

friend class ClassTwo;  
For example,

#include <iostream>
using namespace std;
class Box {
   double width;
   public:
   friend void printWidth( Box box );
   void setWidth( double wid );
};

//成员函数定义
void Box::setWidth( double wid ) {
   width = wid;
}

//注意:printWidth()不是任何类的成员函数。
void printWidth( Box box ) {
   /* Because printWidth() is a friend of Box, it can
   directly access any member of this class */
   cout << "Width of box : " << box.width <<endl;
}

//程序的主要功能
int main() {
   Box box;

   //设置没有成员函数的框宽
   box.setWidth(10.0);

   //使用友元函数打印wdith。
   printWidth( box );

   return 0;
}

输出结果

这将给出输出-

Width of box: 10

即使该函数不是该类的成员,它也可以直接访问该类的成员变量。在某些情况下这可能非常有用。