Friend of Class
A function outside of a class has a special relationship with that class!
Friend relationships provide a mechanism for data sharing between member functions of different classes or objects, and between class member functions and general Functions. In Layman's terms, A friend relationship is a class that proactively declares those other classes or functions to be its friends, and then gives them access concessions for this class.
In a class, you can use the keyword friend to declare other functions or classes as FRIENDS. If a friend is a member function of a generic function or class, it is called a friend function, or if a friend is a class, it is called a friend class. All member functions of the friend class automatically become friend Functions.
1, friend function
A friend function is a non-member function that is decorated with the keyword friend in the class. A friend function can be a normal function, or it can be a member function of another class. Although it is not a member function of this class, the private and protected members of the class can be accessed through the object name in its function body.
Calculate the distance between any two points using the friend function
#include <iostream>
#include <cmath>
Using namespace std;
Class Point//point Classes Definition
{
Public
Point (int xx=0,int yy=0) {x=xx; y=yy;} constructor function
int GetX () {return X;}
int GetY () {return Y;}
Friend float fdist (point &a,point &b);//friend function declaration
Private
int x, y;
};
Float fdist (point &p1,point &p2)
{
Double x=double (p1. x-p2.x);
Double y=double (p1. y-p2.y);
return float (sqrt (x*x+y*y));
}
int main ()
{
Point myp1, myp2 (4,5);
cout<< "the Distance is:";
Cout<<fdist (myp1,myp2) <<endl;
Return 0;
}
2, Friend class
Like a friend function, a class can declare another class as a friend class. If Class A is a friend of class b, all member functions of Class A are friend functions of Class B and can access private and protected members of Class B. The syntax form is as Follows:
Class B
{
...
Friend Class A; Friend class that declares A is B
...
};
Declaring a friend class is a way to establish data sharing between classes and Classes.
Class A
{
Public
void Display () {cout<<x<<endl;}
int Getx () {return x;}
Friend class B;//b class is a friend function of Class A
Private
int x;
}
Class B
{
Public
void Set (int i);
void Display ();
Private
a;
}
void B::set (int I)
{
A.x=i;//because B is a friend of a, you can access the private members of Class A objects in the member function of B
}
In the next chapter, you will use a friend class to implement matrix Calculations.
About friends, There are a few points to note: a, friend relationship is not transitive; b, friend relationship is one-way; c, friend relationship is not inherited, if Class B is a friend of class b, the derived class of Class A does not automatically become a friend of Class A.
Structure of the 3-c++ program 1.3