如果你不选择一个继承类型,c++默认为私有继承(就像默认为私有成员访问如果你不指定其他)。
让我们9组合:3成员访问说明符(公有、私有和保护),和3继承类型(公共、私人和保护)。
本节的其余部分将致力于解释这之间的区别。
在我们开始之前,应该牢记以下我们一步通过例子。有三种方式,成员可以访问:
一个类可以访问它的成员无论访问说明符。
公共访问类的成员的访问说明符类。
派生类访问继承成员基于直接父的访问说明符。一个派生类可以访问它的成员无论访问说明符。
这可能会让人有些迷惑,但希望我们一步通过例子将变得更清楚。
公共继承
公共继承是迄今为止最常用的一种继承。事实上,你将很少使用其他类型的继承,所以你的重点应该是理解本节。幸运的是,公众继承也是最容易理解的。当你继承一个基类公开,所有成员保持原有访问规范。私有成员保持私有,保护成员保持保护,保持公众和公共成员。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
class
Base
{
public
:
int
m_nPublic;
private
:
int
m_nPrivate;
protected
:
int
m_nProtected;
};
class
Pub:
public
Base
{
// Public inheritance means:
// m_nPublic stays public
// m_nPrivate stays private
// m_nProtected stays protected
Pub()
{
// The derived class always uses the immediate parent's class access specifications
// Thus, Pub uses Base's access specifiers
m_nPublic = 1;
// okay: anybody can access public members
m_nPrivate = 2;
// not okay: derived classes can't access private members in the base class!
m_nProtected = 3;
// okay: derived classes can access protected members
}
};
int
main()
{
// Outside access uses the access specifiers of the class being accessed.
// In this case, the access specifiers of cPub. Because Pub has inherited publicly from Base,
// no access specifiers have been changed.
Pub cPub;
cPub.m_nPublic = 1;
// okay: anybody can access public members
cPub.m_nPrivate = 2;
// not okay: can not access private members from outside class
cPub.m_nProtected = 3;
// not okay: can not access protected members from outside class
}
|
这是相当简单的。值得注意的事情是:
派生类不能直接访问基类的私有成员。
受保护访问说明符允许派生类直接访问基类的成员,而不是向公众揭露这些成员。
从基类派生的类使用访问说明符。
外部使用从派生类访问说明符。
总结在表的形式:
私有继承
私有继承,继承基类的所有成员是私有的。这意味着私有成员保持私有,保护和公共成员成为私人。
请注意,这并不影响这样的派生类访问成员继承其父!它只会影响代码试图通过派生类访问这些成员。