【问题标题】:C++11 Allow inheritance only to certain classesC++11 只允许继承某些类
【发布时间】:2014-05-10 12:51:33
【问题描述】:

我有一个基类,我想阻止大多数类继承,但允许它用于少数我可以硬编码的类。这在 C++ 中可能吗?使用 C++11 更容易吗?

我想也许我会使用 final 参数,但这完全阻止了任何继承。

// This can be derived by anyone
class Base{
...
}

// This should only be derived by those I say can derive it
class Base2: public Base{
    protected:
         int SpecialVar;
}

我想要这个的原因是某些类需要访问SpecialVar,而对其他类没有意义。所有类都具有Base 的功能仍然有意义。

【问题讨论】:

  • 您可能需要继承类来实现一个或多个特定接口。
  • 你的基类是抽象的(或者可能是抽象的)?
  • 我真的不希望我的基类是抽象的。它只定义了一些类需要但其他类不需要的一个变量。
  • 您可以前向声明派生类,使它们成为朋友,并使所有构造函数私有。
  • @Jeremy 至于实际的缺点:拥有一个必须手动指定允许的继承者的类将使您在每次需要添加新类时重新编译整个程序,无论出于何种原因。此外,如果其他人觉得有必要,他们将无法扩展您的工作。

标签: c++ inheritance c++11


【解决方案1】:

除了让你的派生类成为朋友之外,另一种方法(这可能有意义也可能没有意义,取决于你正在处理的具体类)是嵌套它们。

class Base {
    Base() { }
public:
    class Derived;
};

class Base::Derived : Base {
};

class CannotDerive : Base {
};

int main() {
    Base::Derived x; // ok
    CannotDerive y; // error
}

【讨论】:

    【解决方案2】:
    class X 
    {   
        private:
            X() {}
    
            friend class D;
    };  
    
    class D: public X
    {   
    };  
    
    class Y: public X // will fail, because it can't access X::X()
    {   
    };  
    

    【讨论】:

      【解决方案3】:

      其他可能性是使用私有析构函数(特别是如果A 是一个抽象类,因为您不需要A 的实例):

      class A
      {
        private:
           virtual ~A() = 0;
      };
      
      A::~A() {}
      
      class B : public A // Compilation error: ~A() is private.
      {};
      

      但是,如果 B 是您有权从 A 继承的类之一,请将其设为 A 的朋友:

      class A
      {
        private:
           friend class B;
           virtual ~A() = 0;
      };
      
      A::~A() {}
      
      class B : public A // Fine.
      {};
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-23
        • 2011-08-11
        相关资源
        最近更新 更多