您的位置:首页 > 其它

私人成员派生类

2014-10-27 14:20 10 查看
前面的课程我们遗传的,我们已经让所有的公共数据成员为了简化的例子。在这一节,我们将谈论在遗传过程访问说明符的作用,以及ascover的不同类型遗传可能在C++。

这一点,你见过的私人和公共接入说明符,它确定谁能访问类的成员。有快速的环境,公众成员可以上网的人。私有成员只能由同一个类的成员函数访问。注意,这意味着不能访问私人成员派生类。

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
};


当处理继承类,事情有点复杂。

第一,有三分之一的访问说明符,我们还谈论因为它是唯一有用的遗传背景。受保护的访问说明符限制访问同一个类的成员函数,或派生类。
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
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐