Friend function
The friend function of a class is defined outside the class, but has access to all private members and protection (protected) members of the class. Although the prototype of a friend function appears in the definition of a class, the friend function is not a member function.
A friend can be a function that is called a friend function; A friend can also be a class that is called a friend class, in which case the entire class and all its members are friends.
If you want to declare the function as a friend of a class, you need to use the keyword friend before the function prototype in the class definition, as follows:
class box{ double width; Public : Double length; void printwidth (box box); void Double wid);};
Declaring all member functions of a class classtwo as Friends of class Classone, you need to place the following declaration in the definition of class Classone:
Friend class Classtwo;
Take a look at the following program:
#include <iostream>using namespacestd;classbox{Doublewidth; Public: Friendvoidprintwidth (box box); voidSetWidth (Doublewid);};//member function DefinitionsvoidBox::setwidth (Doublewid) {Width=wid;}//Please note: printwidth () is not a member function of any classvoidprintwidth (Box box) {/*because PrintWidth () is a friend of Box, it can directly access any member of the class*/cout<<"Width of Box:"<< Box.width <<Endl;} //main function of the programintMain () {box box; //To set the width using member functionsBox.setwidth (10.0); //output width using friend functionprintwidth (box); return 0;}
Compile output:
[Email protected] virtual-machine:~/documents/test/c++/four$./Ten
The use of the friend function
Because the friend function does not have this pointer, there are three conditions for the parameter:
1. To access a non-static member, the object is required to do the argument;
2. To access a static member or global variable, the object is not required to do the argument;
3. If the object that makes the parameter is a global object, then the object does not need to do parameters, you can directly adjust the cell function, do not need to pass the object or pointer
Instance code:
class integer{ void Print (const integer& obj); declare friend function }; void Print (const integer& obj) { // function Body }void Main () { INTEGER obj; Print (obj); // call directly }
C + + parsing four-friend function, inline function, static member