为什么我们在 C++ 中实际上需要 Private 或 Protected 继承?

2023-12-03

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

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

真的有用吗?


当您想要访问基类的某些成员但又不想在类接口中公开它们时,它非常有用。私有继承也可以被视为某种组合:C++ 常见问题解答给出下面的例子来说明这个说法

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
};

为了获得相同的语义,您还可以编写 car 类,如下所示:

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 类的封装,因为您可以访问其受保护的成员
  • 你可以重写 Engine 虚拟方法,如果你的目标是简单的组合,这是你不想要的
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我们在 C++ 中实际上需要 Private 或 Protected 继承? 的相关文章

随机推荐