私有,公共和受保护继承之间的区别 [英] Difference between private, public, and protected inheritance
问题描述
我查看了SO,无法找到 public
, private
之间的区别的良好解释; protected
在C ++中继承。我发现的所有问题都涉及具体案例。一般来说有什么区别?
I looked on SO and couldn't find a good explanation of the difference between public
, private
, and protected
inheritance in C++. All of the questions I've found deal with specific cases. What is the difference in general?
推荐答案
为了回答这个问题,我想先用自己的话来描述成员的访问者。如果你已经知道这一点,请跳到下一个标题。
To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:".
我知道有三个访问器: public
,
protected
和 private
。
There are three accessors that I'm aware of: public
, protected
and private
.
让:
class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};
- 所有知道
Base
也知道
Base
包含publicMember
。 - 只有孩子(及其子女)知道
Base
包含protectedMember
。 - 没有人
基础
知道privateMember
。 - Everything that is aware of
Base
is also aware thatBase
containspublicMember
. - Only the children (and their children) are aware that
Base
containsprotectedMember
. - No one but
Base
is aware ofprivateMember
. - 如果继承为
public
code>基本和子也知道
子
继承自<$如果继承为protected
,则只有及其子项都知道它们继承自
Base
。 - 如果继承为
private
,除了之外没有人知道继承。
- If the inheritance is
public
, everything that is aware ofBase
andChild
is also aware thatChild
inherits fromBase
. - If the inheritance is
protected
, onlyChild
, and its children, are aware that they inherit fromBase
. - If the inheritance is
private
, no one other thanChild
is aware of the inheritance.
意识到,我的意思是承认存在,因此能够访问。
By "is aware of", I mean "acknowledge the existence of, and thus be able to access".
公共,私人和受保护的继承也是如此。让我们考虑从 Base $ c $>继承的类
Base
和类 Child
c>。
The same happens with public, private and protected inheritance. Let's consider a class Base
and a class Child
that inherits from Base
.
这篇关于私有,公共和受保护继承之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!