Example 1: Using the friend function of the class itself
#include <iostream>#include<cmath>using namespacestd;/** Friend function: A friend function can access private members, public members, and protected members. *///Example 1: Using the friend function of the class itselfclassPoint {Private: Doublex, y; Public: Point (DoubleADoubleb) {x=A; Y=b; } DoubleGetX () {returnx; } DoubleGetY () {returny; } //declare a friend function, which is usually outside the class body; it is not a member function of a classFriendDoubleDistance (point&, point&);};//Access private members X and y in the point classDoubleDistance (point &p1, Point &p2) { DoubleDX = p1.x-p2.x; DoubleDY = p1.y-p2.y; returnsqrt (DX*DX + dy*dy);}intMain () {point P1 (1,2), p2 (3,4); Std::cout<< distance (p1, p2) <<Std::endl; return 0;}
Example 2: Use the member function of a class as a friend function
#include <iostream>using namespacestd;/** Friend function * Use the member function of a class as a friend function. Declaration method: Friend function type function class Name: function name (parameter list)*/classboth;//declare class One first so that one references theclassOne {Private: intx; Public: One (inta) {x=A; } intGetX () {returnx; } voidFunc (both &); };classBoth {Private: inty; Public: Both (intb) {y=b; } intGetY () {returny; } //Class One declares the member Func of Class one as a friend function by using the Friend keyword, so the object of one can be//function Func accesses the private member of the objectFriendvoidOne::func (&);};//to modify a private member of a classvoidOne::func (&r) {r.y=x;}intMain () {/*output Result: X:1,y:2 x:1,y:1*/One One (1); Both (2); cout<<"x:"<< One.getx () <<", y:"<< two.gety () <<Endl; One.func (both); cout<<"x:"<< One.getx () <<", y:"<< two.gety () <<Endl; return 0;}
Example 3: Describe a class as a friend of another class
#include <iostream>using namespacestd;/** * Describe a class as a friend of another class * Several points of note: * 1. A friend relationship is not passed, that is, when the description Class A is a friend of Class B, Class B is a friend of Class C, Class A is not a friend of Class C. * 2. When one wants to work with another class, it is useful to use a class as a friend of another class. * 3. Friend declarations are independent of access control, and there is little difference between a friend function in a private area or in a public domain. */classOne ;classBoth {Private: inty; Public: FriendclassOne;//describe one as a friend of the other, so that all of the member functions of one are the friend functions of the other, and you can access the private data of the class from either function. };classOne {Private: intx; Public: One (intA, the &r,intb) {x=A; R.y=b; } voidDisplay (both &r) {cout<<"x:"<< x <<", y:"<< R.y <<Endl; }};intMain () {//output Result: X:1,y:2Twoobj; One oneobj (1, Twoobj,2); Oneobj.display (Twoobj); return 0;}
Friend function Learning in C + +