目录

朋友的功能(Friend Functions)

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

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

要将函数声明为类的朋友,请在类定义中使用关键字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 );
};
// Member function definition
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;
}
// Main function for the program
int main() {
   Box box;
   // set box width without member function
   box.setWidth(10.0);
   // Use friend function to print the wdith.
   printWidth( box );
   return 0;
}

编译并执行上述代码时,会产生以下结果 -

Width of box : 10
↑回到顶部↑
WIKI教程 @2018