Friend is a friend and friend of the class.
Friend function: A friend function of a class can access the private members of the class
We can use the member functions of one class (including constructs, destructors) as friend functions of another class. As follows
classCcar;//declare the Ccar class in advance so that the following Cdriver class uses theclassCdriver { Public: voidModifycar (Ccar *pcar);//Modified Car};classCcar {Private: intPrice ; FriendintMostexpensivecar (Ccar cars[],intTotal);//declare as FriendFriendvoidCdriver::modifycar (Ccar *pcar);//Declare friend};voidCdriver::modifycar (CCAR *Pcar) {Pcar->price + = +;}intMostexpensivecar (Ccar cars[],intTotal ) { intTmpmax =-1; for(inti =0; I < total; ++i) {if(Cars[i].price >Tmpmax) {Tmpmax=Cars[i].price; } } returnTmpmax;}intMain () {return 0;}
Friend class
A is a friend of B, then A's member function can access the private member of B.
Note: Relationships between friend classes cannot be passed and cannot be inherited.
The following code
classCcar {Private: intPrice ; FriendclassCdriver;//declare cdriver as friend class};classCdriver { Public: Ccar MyCar; voidModifycar () {//Modified CarMycar.price + = +; }};intMain () {return 0;}
C + + Friend