为什么我们实际上需要C ++中的私有或保护继承? [英] Why do we actually need Private or Protected inheritance in C++?

查看:152
本文介绍了为什么我们实际上需要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(); //启动此引擎
};

class Car {
public:
Car():e_(8){} //使用8个气缸初始化这个Car
void start(){e_。开始(); } //通过启动它的Engine启动这个car
private:
Engine e_; // Car has-a Engine
};

要获得同样的语义,你也可以写如下的车类:

  class Car:private Engine {// Car has-a Engine 
public:
Car():Engine {} //使用Engine :: start初始化这个Car with 8 cylinders
// Start this Car by starting its Engine
};但是,这种做法有几个缺点:










b

  • 您的意图不太清楚

  • 它可能导致滥用的多重继承

  • 因为您可以访问其受保护的成员

  • ,您可以覆盖Engine虚拟方法,这是您不想要的,如果您的目标是一个简单的组合


In C++, I can't think of a case in which I would like to inherit private/protected from a base class:

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

Is it really useful?

解决方案

It is useful when you want to have access to some members of the base class, but without exposing them in your class interface. Private inheritance can also be seen as some kind of composition: the C++ faq-lite gives the following example to illustrate this statement

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

To obtain the same semantic, you could also write the car Class as follow:

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

However, this way of doing has several disadvantages:

  • your intent is much less clear
  • it can lead to abusive multiple inheritance
  • it breaks the encapsulation of the Engine class since you can access its protected members
  • you're allowed to override Engine virtual methods, which is something you don't want if your aim is a simple composition

这篇关于为什么我们实际上需要C ++中的私有或保护继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆