【问题标题】:Inheriting from protected classes in C+++从 C++ 中的受保护类继承
【发布时间】:2010-09-14 07:11:54
【问题描述】:

假设我有以下声明:

class Over1
{
   protected:
      class Under1
      {
      };
};

我知道我可以做到以下几点:

class Over2 : public Over1
{
   protected:
        class Under2 : public Under1
        {
        };
};

但是有没有办法在没有 Over2 的情况下声明 Under2?

由于您必须扩展 Over1 以使用 Under1 的任何派生,这可能看起来很愚蠢,但在这种情况下可能有 30 种不同风格的 Under。我可以:

  • 将它们全部放在 Over1 中:不 有吸引力,因为 Over2 只能使用 其中1或2个
  • 将它们分别放入 他们自己的 Over 版本:不是 有吸引力,从那时起你将拥有 乘以几乎从 同班。
  • 找到一种方法来创建 未创建的 Under1 的孩子 Over1的孩子

那么这可能吗?

谢谢。

【问题讨论】:

    标签: c++ inheritance oop private


    【解决方案1】:

    比创建嵌套类更好的是,您可能希望将这些类嵌入到命名空间中。这样,您就不需要外部类来获取内部类。在Google C++ Style Guide 中有一些支持和反对的重要论据。

    【讨论】:

      【解决方案2】:

      使用模板和显式特化,您只需在 Over1 中添加一个类声明即可做到这一点。

      class Over1
      {
      protected:
        class Under1
        {
        };
      
        template <typename T>
        class UnderImplementor;
      };
      
      struct Under2Tag;
      struct Under3Tag;
      struct Under4Tag;
      
      template <>
      class Over1::UnderImplementor<Under2Tag> : public Over1::Under1
      {
      };
      
      template <>
      class Over1::UnderImplementor<Under3Tag> : public Over1::Under1
      {
      };
      
      template <>
      class Over1::UnderImplementor<Under4Tag> : public Over1::Under1
      {
      };
      

      希望这会有所帮助。

      【讨论】:

        【解决方案3】:

        如果您想保护 Under1,那么根据定义,您需要从 Over1 继承才能访问它。我建议将 Under1 公开,或者按照 Douglas 的建议使用命名空间。

        我现在没有编译器来测试这些,所以我完全不确定这些是否可行,但你可以试试这个:

        class Over1
        {
           protected:
              class Under1
              {
              };
        
           public:
              class Under1Interface : public Under1 
              {
              };
        };
        
        class Under2 : public Over1::Under1Interface
        {
        };
        

        或者可能是这样的:

        class Over1
        {
           protected:
              class Under1
              {
              };
        };
        
        class Under2 : private Over1, public Over1::Under1
        {
        };
        

        甚至:

        class Under2;
        
        class Over1
        {
           friend class Under2;
        
           protected:
              class Under1
              {
              };
        };
        
        class Under2 : public Over1::Under1
        {
        };
        

        虽然这会将所有 Over1 的私人信息暴露给 Under2 - 这可能不是你想要的。

        【讨论】:

          【解决方案4】:

          对我来说听起来有点时髦。为什么不尝试以不同的方式构建代码。我认为这可能是装饰器模式的一个很好的候选者,您可以将基类包装在各种装饰器中以实现所需的功能,“under”的各种风格可能是装饰器。只是一个想法,如果不进一步了解代码的意图,很难说清楚。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-09-04
            • 2020-09-09
            • 2016-06-12
            • 2014-06-09
            • 2014-06-29
            • 1970-01-01
            • 2018-03-26
            • 2023-03-03
            相关资源
            最近更新 更多