C++ friend class usage (friend)

Private variables in C++ cannot be directly accessed by external classes, nor can they be inherited.

Using friend classes can access private methods and private variables in the class. Although it has certain damage to the encapsulation of the class, it is sometimes very practical.

In practice, when modifying existing code, sometimes in order to not change the existing code, it is more friendly to use friend class .

 

Look directly at the code example:

a.h

1 #include<stdio.h>
 2  // Note: Do not include bh in this class file, otherwise an error will be reported
 3  
4  // Note: Since it is not the same namespace, declare class B2 
5  namespace st1{
 6  namespace st2 {
 7  class B2; 
 8  }
 9  }
 10  
11  class A{
 12  public :
 13      void print(){
 14          printf( " A print function\n " );
 15      }   
 16  
17  private :
 18      void_inner_print(){
 19          printf( " A print _inner_print\n " );
 20      }   
 21  
22      // Note: Declare a friend class, so that two classes can directly access private variables, function 
23      friend class B1; 
 24      friend class : :st1::st2::B2;
 25      
26 };

b.h

 1 #include "a.h"
 2 
 3 //定义B1
 4 class B1{ 
 5 public:
 6     void print(){
 7         printf("\ncall B1 print\n");
 8         a.print();
 9         a._inner_print();
10     }   
11 
12 private:
13     A a;    
14 };
15 
16 //定义B2
17 namespace st1{
18 namespace st2{
19 
20 class B2{ 
21 public:
22     void print(){
23         printf("\ncall B2 print\n");
24         a.print();
25         a._inner_print();
26     }   
27 
28 private:
29     A a;    
30 };
31     
32 }
33 }

Test file main.cpp

 1 #include <stdio.h>
 2 #include "b.h"
 3 
 4 int main(){
 5     B1 b1; 
 6     ::st1::st2::B2 b2; 
 7 
 8     b1.print();
 9     b2.print();
10     return 0;
11 }

output:

call B1 print
A print function
A print _inner_print

call B2 print
A print function
A print _inner_print

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324689340&siteId=291194637