简体   繁体   English

控制对班级成员的访问

[英]Controlling Access to Class Members

class A
{
   private:
           int x;
   public:
           virtual void show()
           {
               cout<<"X: "<<x;
           }
};

class B: public A
{
    public:
           virtual void show()
           {
               cout<<"In class B\n";
               A::show();
           }
};

My question is about accessibility from a member function. 我的问题是关于成员函数的可访问性。 In this example, can we say that member function of B (show() of B) can access X in the class A. 在此示例中,我们可以说B的成员函数(B的show())可以访问类A中的X。

Since x is declared private in A , nothing in B can directly access it. 由于xA被声明为private ,因此BA任何人都无法直接访问它。 Of course, it can be accessed indirectly -- B can call A::show() which can access x . 当然,它可以间接访问B可以调用A::show()来访问x But B::show() cannot access x , nor can anything else in B . 但是B::show()不能访问x ,也不能什么都在B

You are not really accessing Ax , you are accessing A.show() . 您实际上不是在访问Ax ,而是在访问A.show()

To answer your question, B::show() is not accessing the private member x in A . 为了回答您的问题, B::show() 没有访问A的私有成员x

The reason for this is, class A can change the function A::show() and do something else, and B can just call A::show() . 原因是, class A可以更改函数A::show()并执行其他操作,而类B可以仅调用A::show()

This is the main point of encapsulation. 这是封装的要点。 You can tell A to do things (like show() ), but A decides how to do them. 您可以告诉A做事情 (例如show() ),但是A决定如何做。

  1. A::show() can access any member variables in it's own class, class A. A :: show()可以访问其自己的类A中的任何成员变量。
  2. Member functions in class B can access any public or protected member variables in class A. B类中的成员函数可以访问A类中的任何公共或受保护的成员变量
    and
  3. Member functions in class B can access any public of protected member functions in class A. B类中的成员函数可以访问A类中任何受保护成员函数的公共对象。

2 and 3 are possible because the "Most accessible level" of A is defined as public. 因为A的“最易访问级别”被定义为公共,所以图2和图3可能出现。

Class B: public A

In your code, specifically, the accessibility level of int x; 在您的代码中,特别是int x;的可访问性级别int x; doesn't matter, because it is never directly accessed from class B. 没关系,因为永远不会从B类直接访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM