派生类到基类转换的可访问性

 

 在看C++ primer中的关于派生类到基类转换的可访问性的问题时,对于以下:

  • 如果是public继承,则用户代码和后代码类都可以使用派生类到基类的转换。如果类是使用privateprotected继承派生的,则用户代码不能将派生类型对象转换为基类对象。如果是private继承,则从private继承类派生的类不能转换为基类。如果是protected继承,则后续派生类的成员可以转换为基类类型。  
  • 对比英文版:  
  • If the inheritance is public, then both user code and  
  • member functions of subsequently derived classes may use  
  •  the derived-to-base conversion. If a class is derived   
  • using private or protected inheritance, then user code   
  • may not convert an object of derived type to a base type   
  • object. If the inheritance is private, then classes   
  • derived from the privately inherited class may not   
  • convert to the base class. If the inheritance is   
  • protected, then the members of subsequently derived   
  • classes may convert to the base type.  
  • 另外有一个Tips:  
  • To determine whether the conversion to base is accessible, consider whether a public member of the base class would be accessible. If so, the conversion is accessible; otherwise, it is not.  
  • 中文版上是:  
  • 要确定到基类的转换是否可访问,可以考虑基类的public成员是否可访问,如果可以,转换是可访问的,否则,不可访问

     

    一开始很久不能理解,在网上查了一下,有些许多的理解,但是感觉没有自己满意的,反复看了几篇,似乎有些明了,现写下来,不知道对不对,若又不对之处,希望有人留言,非常感谢

     

    个人觉得应该归纳为一下几点:

     首先假定基类a成员都是public的

    (1)如果是public继承,那么如果类b是public继承基类a派生的时,则用户代码(对类的操作)和后代类(应该理解为派生类b的派生类c,同样也是public继承派生)都可以使用派生类到基类的转换。

      (4)   如果类是使用privateprotected继承派生的,则用户代码(对类的操作)不能将派生类型对象(类b的实例)转换为基类对象(类a的实例)(因为基类a都是public类型的,而派生之后只能是private或者protected的,显然是不可以转换的)。

    (2)如果是private继承,则从private继承类(此时基类在派生类b中的成员都是private类型的)派生的类(这个类c将会不可访问b中基类a中的成员,因为此时基类a中的成员在类b已经都是private的,类c不会继承类a的任何成员了)不能转换为基类。

    (3)如果是protected继承,则后续派生类(类b的派生类c)的成员(成员函数,借助自身成员函数实现)可以转换为基类类型(类a)(因为protected继承,自然派生类可以对基类成员进行访问的,派生类中自然继承基类中的成员,只是访问限制改为了protected)(!如果直接对类c转换成类a,是不可以的,见(4))。  

    参考:
  • http://blog.csdn.net/roden/article/details/5413371
  • http://blog.sina.com.cn/s/blog_4017cf060100gz3d.html
  • http://blog.csdn.net/roden/article/details/5413371
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值