Latest web development tutorials

C ++ friend function

C ++ Class & Objects C ++ Class & Objects

Class friend function is defined outside the class, but the class has access to all private (private) members and protection (protected) members. Although the prototype friend functions defined in the class appeared, but the friend function is not a member function.

Friend can be a function that is called the friend function; friend can also be a class that is called the friend class, in this case, the class as a whole and all its members are a friend.

If you want to declare a function as a friend of a class, you need to use a keyword before the function prototypefriend in the class definition, as follows:

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

All members of the class declaration ClassTwo function as a kind of ClassOne friend, need to be placed in the class definition ClassOne the following statement:

friend class ClassTwo;

Consider the following program:

#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 )
{
   /* 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员 */
   cout << "Width of box : " << box.width <<endl;
}
 
// 程序的主函数
int main( )
{
   Box box;
 
   // 使用成员函数设置宽度
   box.setWidth(10.0);
   
   // 使用友元函数输出宽度
   printWidth( box );
 
   return 0;
}

When the above code is compiled and executed, it produces the following results:

Width of box : 10

C ++ Class & Objects C ++ Class & Objects