对于C++保护继承方式的一点理解

最近在某书上看到这样一句话--“所以,在保护继承时,基类的成员也只能由直接派生类访问,而无法再往下继承。”

有图有真相,上个书的截图如下:

 

对此,我疑问不解,一直觉得只是将public,降级到了protected,怎么会“只能由直接派生类访问,而无法再往下继承”呢??我编了如下代码为验证这个问题:

class Base
{
public:
 void print()
 {
  cout << "class Base" << endl;
 }
 Base()
 {
  i = 10;
 }
protected:
 int i;
};

class Drived: protected Base
{
public:
 void print()
 {
  cout << "class Drived: public Base" << endl;
 }
};

class DrivedSub: protected Drived
{
public:
 void print()
 {
  cout << "Sub drived class is " << i << endl;
 }
};

int _tmain(int argc, _TCHAR* argv[])
{

 DrivedSub ds;
 ds.print();
 return 0;

}

结果正确的输出:Sub drived class is 10

说明在protected继承时,间接的子类中是可以访问基类的protected的。同理,public成员也是可以访问的。

 

以上仅一家之言,欢迎大家拍砖。

 

百度搜了一下,错误的文章还不少,大家都是抄来抄去的:

http://www.baidu.com/s?tn=baiduhome_pg&bs=protected%C1%BD%B4%CE%BC%CC%B3%D0&f=8&rsv_bp=1&wd=%CB%F9%D2%D4%A3%AC%D4%DA%B1%A3%BB%A4%BC%CC%B3%D0%CA%B1%A3%AC%BB%F9%C0%E0%B5%C4%B3%C9%D4%B1%D2%B2%D6%BB%C4%DC%D3%C9%D6%B1%BD%D3%C5%C9%C9%FA%C0%E0%B7%C3%CE%CA&inputT=26943

 

http://media.openonline.com.cn/media_file/200708/fushi/0803/C++yuyancxsj/web/lesson/chapter18/j6.htm

http://hi.baidu.com/rainysky_2006/blog/item/c9dfdb3dceb270c79e3d6230.html

http://hi.baidu.com/wentaokou/blog/item/a2541ccfff26ac0e93457ef6.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值