c ++ friend function the third time jobs

Friend function

definition:

Class friend function is defined outside the class, but all the members of the private and protected members of the class have access. Although the prototype friend functions defined in the class appeared, but the friend function is not a member function.

Friend may be a function that is called friend function; friend can be a class that is called a friend class, in this case, the entire class and all members are friend.

If you declare a function as a friend of a class, use the keyword friend before the function prototype in the class definition.

code show as below:

class A
{
public:
   int m,s,h;
   friend class B;
};

After the statement B is a member function A friend function, access to A's private and protected members.

Example:

#include <bits/stdc++.h>
using namespace std;
class Clock
{
    public:
    friend void showtime(Clock B);
    void settime(int hh,int mm,int ss);
    private:
    int h,m,s;
};
void Clock::settime(int hh,int mm,int ss)
{
    h=hh,m=mm,s=ss;
}
void showtime(Clock B)
{
    cout<<B.h<<":"<<B.m<<":"<<B.s<<endl;
}
int main()
{
    Clock A;
    A.settime(2,3,4);
    showtime(A);
    return 0;
}

Implementation of the results:

Note the use of friend classes:

             (1) Friendship is not inherited. 
             (2) friend relationship is unidirectional, not commutative. If class B is a friend of class A, class A is not necessarily a friend of class B, depending on whether there is a corresponding statement in the class.
             (3) friendship is not transitive. If class B is a friend of class A, class B is a friend of C, C is not necessarily the friend class A, if a corresponding class declaration similar look

Guess you like

Origin www.cnblogs.com/aaddvvaanntteezz/p/11610486.html