继承可能在c++

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

第二,当一个派生类从基类继承,访问说明符可能会改变取决于继承的方法。有三种不同的方法从其他类继承类:公共,私人和保护。

这样做,只需指定你想要哪种类型的访问在选择继承的类:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值