c++私有继承有什么用

Private Inheritance
C++ has a second means of implementing the has-a relationship: private inheritance.With private inheritance, public and protected members of the base class become private members of the derived class.This means the methods of the base class do not become part of the public interface of the derived object.They can be used, however, inside the member functions of the derived class.
Let’s look at the interface topic more closely.With public inheritance, the public methods of the base class become public methods of the derived class. In short, the derived class inherits the base-class interface.This is part of the is-a relationship.With private inheritance, the public methods of the base class become private methods of the derived class. In short, the derived class does not inherit the base-class interface.As you saw with contained objects, this lack of inheritance is part of the has-a relationship.    

以上文字摘抄自《c++ primer plus》 

总结: 私有继承可以实现 has a 的关系,也就是包含。

私有继承中:

1. 父类的 public 和 protected 成员在子类中变成了子类 private 的成员, 

    1.1 这就意味着从父类继承过来的这些成员(public/protected), 子类的成员函数可以调用之;

          但是子类的对象就不能够调用之;

    进一步的理解就是,在 子类中可以调用父类的(public/private)接口, 但是这些接口不会被暴露出去。

这个特性正好实现了包含(composite)的特性。


详细示例,大家可以参考《c++ primer plus》, 14章:reusing code in c++ 之 private inheritace.



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值