代码之家  ›  专栏  ›  技术社区  ›  Whaledawg

从C中的受保护类继承+++

  •  3
  • Whaledawg  · 技术社区  · 17 年前

    假设我有以下声明:

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

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

    但是有没有一种方法可以在不超过2的情况下申报低于2的数据呢?

    • 有吸引力,因为超过2只可能使用 其中1或2个
    • 把它们都放进去 从那以后你就有了魅力
    • 找到一种创造的方法 未满1岁的儿童,不创造

    4 回复  |  直到 17 年前
        1
  •  1
  •   Douglas Mayle    17 年前

    与创建嵌套类相比,您可能需要考虑将这些closs嵌入到名称空间中。这样,就不需要外部类来获取内部类。在这场辩论中,有很多赞成和反对的理由 Google C++ Style Guide .

        2
  •  1
  •   Richard Corden    17 年前

    使用模板和显式专门化,您只需在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
  •  0
  •   Salman A    17 年前

    我现在没有编译器来测试这些,所以我根本不确定这些是否有效,但您可以尝试以下方法:

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

    虽然这会让所有1岁以上的人都暴露在2岁以下的人面前,但这不太可能是你想要的。

        4
  •  0
  •   jhufford    17 年前

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