c++派生类的访问

 1 #pragma once
 2 
 3 #include <iostream>
 4 
 5 namespace WYP
 6 {
 7     class CBase
 8     {
 9     public:
10         int m_BasePublic;
11 
12         void setY(int y) {m_y = y;}
13         void setZ(int z) {m_z = z;}
14         int getX() {return m_x;}
15         int getZ() {return m_z;}
16 
17     protected:
18         void setX(int x) {m_x = x;}
19         int m_z;
20     private:
21         int m_x;
22         int m_y;
23         
24     };
25 
26     class CDivedA : public CBase
27     {
28     public:
29         void setXandZ(int x)
30         {
31             setX(x);//0.派生类的公有成员函数可以访问基类的保护成员函数吗?,可以
32             m_z = x;//1.派生类的公有成员函数可以访问基类的保护成员变量吗?,可以
33         }
34 
35     protected:
36         void setXX(int x)
37         {
38             m_XX = x;
39             setX(x);//00.派生类的保护成员函数可以访问基类的保护成员函数吗?,可以
40             m_z = x;//11.派生类的保护成员函数可以访问基类的保护成员变量吗?,可以
41         }
42 
43     private:
44         int m_XX;
45         int m_YY;
46         int m_ZZ;
47     };
48 
49     void fun()
50     {
51         CBase a;
52         //a.setX(3);//2.类的对象不能访问类的保护成员函数;
53         //a.m_z = 3;//3.类的对象不能访问类的保护成员变量
54 
55         CDivedA b;
56         b.setXandZ(5);
57         //b.setX(1);//3.派生类的对象不能访问基类的私有的、保护的成员函数;
58         //b.m_z = 3;//4.派生类的对象不能访问基类的私有的、保护的成员变量
59 
60         std::cout << b.getX() << std::endl;//5.派生类的对象只可以访问基类的公有成员函数、公有成员变量
61         b.m_BasePublic = 1;//5.派生类的对象只可以访问基类的公有成员函数、公有成员变量
62     }
63 }
原文地址:https://www.cnblogs.com/forgood/p/3400592.html