类的友元函数是在该类的范围之外定义的,但是它有权访问该类的所有私有成员和受保护成员。即使友元函数的原型出现在类定义中,朋友也不是成员函数。
朋友可以是函数,函数模板或成员函数,也可以是类或类模板,在这种情况下,整个类及其所有成员都是朋友。
要将函数声明为类的朋友,请在类定义中的函数原型之前添加关键字friend,如下所示:
class Box { double width; public: double length; friend void printWidth( Box box ); void setWidth( double wid ); };
要将类ClassTwo的所有成员函数声明为类ClassOne的好友,请将以下声明放在类ClassOne的定义中:
friend class ClassTwo;
#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; } // Note: printWidth() is not a member function of any class. 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
即使该函数不是该类的成员,它也可以直接访问该类的成员变量。在某些情况下这可能非常有用。