(笔记):组合and继承之访问限制(二)

上篇简单介绍了public与private的基本使用。private的访问限制相对复杂。针对这种访问属性,我们会想到有没有一种方式可以无视这种属性。
答案是:有。我们可以通过friend的方式(可以破解private与protected的限制)。
即我们在类中声明某个非类成员函数或者其他类的成员函数或者整个类来让这些被声明为friend的东西可以访问private成员变量或成员函数
这种声明为友元的方式有三种:
1、普通函数即非类成员函数
2、类的成员函数
3、整个类

下面代码是分别展示三种情况:

 1 #include<iostream>
 2 using namespace std;
 3 
 4 class Box;
 5 class X{
 6     public:
 7         void print( Box *p);
 8 
 9 }; 
10 
11 class Student {
12     public:
13         Student(){}
14             void print( Box *p);
15 };
16 class Box {  
17 
18    public:
19        Box(){}
20          Box(int width , int height);  
21                  
22         friend void Bss( Box *x);                 //1、外部非类函数 
23         friend struct X;                            //2、整个X类都可以访问该类的private 
24         friend void Student::print(Box *p);    //3、说明X类里面的d函数可以访问私有成员 
25         
26     private:   
27         int m_width;
28     protected:
29         int m_height;
30     
31 };  
32 
33 //Box类 成员函数 
34 Box::Box(int width ,int height):m_width(width) ,m_height(height)
35 {    
36 } 
37 //X类的  成员函数 
38 void X::print(Box *p){
39     cout<<"X::print "<<p->m_width<<endl;     
40 }
41 //Student成员函数 
42 void Student:: print( Box *p){
43     cout<<"Student::print "<<p->m_width<<endl;
44 } 
45 void Bss( Box *x){
46     printf("Bss::print %d
",x->m_height);
47 }
48 
49 int main(){  
50   
51    Box box1(1 ,3);
52     Student a; 
53     X b; 
54    Bss( &box1);    //外部函数 
55    a.print(&box1);//Student类成员函数 
56    b.print(&box1);//X类为友元,其print成员函数 //这里假设参数是box1的对象 也是可以的
57    
58     return 0;    
59 } 

结果:

原文地址:https://www.cnblogs.com/newneul/p/7657966.html