in the previous lessons我们遗传的,我们已经让所有的公共数据成员in order to简化的例子在这一节,我们将谈论the role of Access specifiers in the遗传过程,as well as cover the不同类型遗传可能在C + +
这一点,你见过的私人和公共接入specifiers,which确定谁能访问the members of aclass有快速的环境,公众成员可以上网的人Private Members只能accessed bymember functions of the same class注意,这意味着不能访问private成员派生类
1
2
3
4
5
6
7
|
class
Base
{
private
:
int
m_nPrivate;
// can only be accessed by Base member functions (not derived classes)
public
:
int
m_nPublic;
// can be accessed by anybody
};
|
当dealing with继承的类,事情变得有点更复杂
第一,There is a third访问规定that we have yet to talk about因为只有useful in an遗传背景the protected访问规定restricts access to member functions of the sameclass,or those of衍生类
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
|
class
Base
{
public
:
int
m_nPublic;
// can be accessed by anybody
private
:
int
m_nPrivate;
// can only be accessed by Base member functions (but not derived classes)
protected
:
int
m_nProtected;
// can be accessed by Base member functions, or derived classes.
};
class
Derived:
public
Base
{
public
:
Derived()
{
// Derived's access to Base members is not influenced by the type of inheritance used,
// so the following is always true:
m_nPublic = 1;
// allowed: can access public base members from derived class
m_nPrivate = 2;
// not allowed: can not access private base members from derived class
m_nProtected = 3;
// allowed: can access protected base members from derived class
}
};
int
main()
{
Base cBase;
cBase.m_nPublic = 1;
// allowed: can access public members from outside class
cBase.m_nPrivate = 2;
// not allowed: can not access private members from outside class
cBase.m_nProtected = 3;
// not allowed: can not access protected members from outside class
}
|
第二,当一个派生类从基类继承的访问说明符,可以根据继承法的变化。有从其他类继承的类三种不同的方式:公共,私人,和保护。
这样做,只需指定类型的访问的时候你想选择类继承自:
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继承类型(公共,私人,和保护)。
本节的其余部分将致力于解释它们之间的区别。
在我们开始之前,应牢记,当我们走过的例子。有三种方法可以访问的成员:
一个类可以访问无论访问说明符它自己的成员。
公共访问基于该类的一个类的成员的访问说明符。
派生类继承的成员的访问基于其直接父访问说明符。派生类可以访问无论访问说明符它自己的成员。
这可能有点混乱,但希望将成为我们一步通过实例清楚。