Introduction to the usage example of C++ Friend of Friend

  • 2020-04-02 02:40:45
  • OfStack

Compared with Java, friend is a special element in C++, which is seldom introduced in many textbooks. Therefore, it is not easy to master it when you first learn it. This paper summarizes the use of friend and some points of attention for your reference. Hope to learn C++ friends to play a little help.

Operation steps:

1) in the MyFriend class, define the Father class as a friend element
2) write a Son class inherited from the Father class
3) create the MyFriend object in the constructor of the Father class and the Son class, respectively, and define its three internal variables
4) create the Father object in the constructor of the MyFriend class and define its three internal variables

Results and precautions:

1) the MyFriend object created in the Father class allows direct access to all variables in the MyFriend class
2) the MyFriend object created in the Son class only allows direct access to the Public variable in the MyFriend class
3) from the second point, we can see that the friend relationship cannot be inherited
4) the Father object created in the MyFriend class only allows direct access to the Public variable in the Father class
5) according to the fourth point, the friend relationship is one-way, that is, A is the friend of B, and B is not the friend of A, which needs to be defined separately

The myfriend.h page code is as follows:


#include "Father.h" 
 
class MyFriend{ 
  friend class Quote; //Friend classes are simply defined like this
public: 
  MyFriend(){ 
    Father *p = new Father(); 
    p->var1 = 1; 
    p->var2 = 1; 
    p->var3 = 1; 
  } 
  int var1; 
protected: 
  int var2; 
private: 
  int var3; 
}; 

Father. H page code is as follows:


#include "MyFriend.h" 
 
class Father{ 
public: 
  Father(){ 
    MyFriend *p = new MyFriend(); 
    p->var1 = 1; 
    p->var2 = 1; 
    p->var3 = 1; 
  }; 
  int var1; 
protected: 
  int var2; 
private: 
  int var3; 
} 

The code of son.h page is as follows:


#include "MyFriend.h" 
 
class Son : Father{ 
  Son(){ 
    MyFriend *p = new MyFriend(); 
    p->var1 = 1; 
    p->var2 = 1; 
    p->var3 = 1; 
  }; 
}

Interested readers can debug and run this example, I believe that there will be new results.


Related articles: