c++私有继承有什么用

来源:互联网 发布:辐射4优化mod 编辑:程序博客网 时间:2024/04/30 15:52
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.



0 0
原创粉丝点击