[英]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. 由于x
在A
被声明为private
,因此B
中A
任何人都无法直接访问它。 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
决定如何做。
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.