其他分享
首页 > 其他分享> > 类的访问修饰符

类的访问修饰符

作者:互联网

数据封装是面向对象编程的一个重要特点,它防止函数直接访问类类型的内部成员。类成员的访问限制是通过在类主体内部对各个区域标记 public、private、protected 来指定的。关键字 public、private、protected 称为访问修饰符。一个类可以有多个 public、protected 或 private 标记区域。每个标记区域在下一个标记区域开始之前或者在遇到类主体结束右括号之前都是有效的。成员和类的默认访问修饰符是 private。

在继承中的特点:

但无论哪种继承方式,上面两点都没有改变:

 

#include <iostream>
 
using namespace std;
 
 class test_A
 {
public:
     int A_public ;

     test_A()
     {
        A_public = 202;
        A_protected = 10;
        A_private = 100;
     }

     void foo()
     {
         cout << "A_public : " << A_public << endl;
         cout << "A_protected : " << A_protected << endl;
         cout << "A_private : " << A_private << endl;
     }

protected:
     int A_protected;

private:
     int A_private;

 };

 class test_B : public test_A
 {
public:
     int B_public ;

     test_B(int a)
     {
        test_A();
        B_public = a;
     }

     void foo()
     {
         cout << "B_public : " << B_public << endl;
         cout << "A_public : " << A_public << endl;
         cout << "A_protected : " << A_protected << endl;
        //  cout << "A_private : " << A_private << endl; //这条语句是错的,继承类不能访问父类private成员
     }
 };

  class test_C : protected test_A
 {
public:
     int C_public ;

     test_C(int a)
     {
         test_A();
        C_public = a;
     }

     void foo()
     {
        cout << "C_public : " << C_public << endl;
         cout << "A_public : " << A_public << endl;
         cout << "A_protected : " << A_protected << endl;
        //  cout << "A_private : " << A_private << endl; //这条语句是错的,继承类不能访问父类private成员
     }

 };

   class test_D : private test_A
 {
public:
     int D_public ;

     test_D(int a)
     {
         test_A();
        D_public = a;
     }

     void foo()
     {
        cout << "C_public : " << D_public << endl;
         cout << "A_public : " << A_public << endl;
         cout << "A_protected : " << A_protected << endl;
        //  cout << "A_private : " << A_private << endl; //这条语句是错的,继承类不能访问父类private成员
     }

 };

int main ()
{
 test_A A;
 A.foo();

test_B B(300);
B.foo();

test_C C(400);
C.foo();
// C.A_protected; //protected不能在类外访问 
// C.A_private; //private不能在类外访问 

test_D D(500);
D.foo();

   return 0;
}

 

标签:成员,修饰符,private,访问,protected,派生类,public
来源: https://www.cnblogs.com/boost/p/16246752.html