第二,当一个派生类从基类继承的访问说明符,可以根据继承法的变化。有从其他类继承的类三种不同的方式:公共,私人,和保护。
这样做,只需指定类型的访问的时候你想选择类继承自:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Inherit from Base publicly
class Pub: public Base
{
};
// Inherit from Base privately
class Pri: private Base
{
};
// Inherit from Base protectedly
class Pro: protected Base
{
};
class Def: Base // Defaults to private inheritance
{
};
如果你不选择一个继承类,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
}