继承可能在c++

来源:互联网 发布:mmd古风动作数据 编辑:程序博客网 时间:2024/05/16 17:20

在继承之前的教训,我们已经使我们所有的公共数据成员为了简化的例子。在本节中,我们将讨论访问说明符的作用在继承过程中,以及涵盖不同类型的继承可能在c++。

至此,您已经看到了私人和公共访问说明符,决定谁可以访问类的成员。作为一个快速复习,公共成员可以被任何人访问。私有成员只能由同一个类的成员函数访问。请注意,这意味着派生类不能访问私有成员!

1
2
3
4
5
6
7
classBase
{
private:
    intm_nPrivate; // can only be accessed by Base member functions (not derived classes)
public:
    intm_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
classBase
{
public:
    intm_nPublic; // can be accessed by anybody
private:
    intm_nPrivate; // can only be accessed by Base member functions (but not derived classes)
protected:
    intm_nProtected; // can be accessed by Base member functions, or derived classes.
};
 
classDerived: publicBase
{
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
    }
};
 
intmain()
{
    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
classPub: publicBase
{
};
 
// Inherit from Base privately
classPri: privateBase
{
};
 
// Inherit from Base protectedly
classPro: protectedBase
{
};
 
classDef: Base // Defaults to private inheritance
{
};

0 0
原创粉丝点击