私有、公共和受保护继承之间的区别 [英] Difference between private, public, and protected inheritance
问题描述
C++ 中的public
、private
和protected
继承有什么区别?
What is the difference between
public
,private
, andprotected
inheritance in C++?
我在 SO 上发现的所有问题都涉及特定案例.
All of the questions I've found on SO deal with specific cases.
推荐答案
为了回答这个问题,我想先用我自己的话来描述成员的访问器.如果您已经知道这一点,请跳到标题下一个:".
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
. - 除了
Base
没有人知道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
,所有知道Base
和Child
的东西也知道Child
继承自Base
. - 如果继承是
protected
,则只有Child
及其子代知道它们从Base
继承. - 如果继承是
private
,那么除了Child
之外没有人知道继承. - 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
和一个继承自 Base
的类 Child
.
The same happens with public, private and protected inheritance. Let's consider a class Base
and a class Child
that inherits from Base
.
这篇关于私有、公共和受保护继承之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!