为什么我们实际上需要C ++中的私有或受保护的继承?

在C ++中,我想不出一个我想从基类继承private / protected的情况:

class Base;
class Derived1 : private Base;
class Derived2 : protected Base;

它真的有用吗?


当你想访问基类的一些成员,但没有将它们暴露在你的类接口中时,这很有用。 私有继承也可以被看作是某种组合:C ++ faq-lite给出了下面的例子来说明这个语句

class Engine {
 public:
   Engine(int numCylinders);
   void start();                 // Starts this Engine
};

class Car {
  public:
    Car() : e_(8) { }             // Initializes this Car with 8 cylinders
    void start() { e_.start(); }  // Start this Car by starting its Engine
  private:
    Engine e_;                    // Car has-a Engine
};

为了获得相同的语义,你也可以写汽车类如下:

class Car : private Engine {    // Car has-a Engine
 public:
   Car() : Engine(8) { }         // Initializes this Car with 8 cylinders
   using Engine::start;          // Start this Car by starting its Engine
}; 

但是,这种做法有几个缺点:

  • 你的意图不太清楚
  • 它会导致滥用多重继承
  • 它打破了Engine类的封装,因为您可以访问其受保护的成员
  • 你可以重写引擎虚拟方法,如果你的目标是一个简单的组合,这是你不想要的东西

  • 私人在很多情况下都可以使用。 其中之一就是政策:

    部分类模板专业化是这个设计问题的答案吗?

    另一个有用的场合是禁止复制和分配:

    struct noncopyable {
        private:
        noncopyable(noncopyable const&);
        noncopyable & operator=(noncopyable const&);
    };
    
    class my_noncopyable_type : noncopyable {
        // ...
    };
    

    因为我们不希望用户有一个类型为noncopyable*的指针给我们的对象,所以我们私下导出。 这不仅包括不可复制的,也包括许多其他类(政策是最常见的)。


    公共继承模型IS-A。
    非公有继承模型IS-IMPLEMENTED-IN-TERMS-OF。
    遏制模型HAS-A相当于IS-IMPLEMENTED-IN-TERMS-OF。

    萨特在这个话题上。 他解释了何时选择非公有继承来控制实施细节。

    链接地址: http://www.djcxy.com/p/13779.html

    上一篇: Why do we actually need Private or Protected inheritance in C++?

    下一篇: Does malloc create a new instance of the class or not?