【问题标题】:How to create a class that can not be inherited by other classes? [duplicate]如何创建一个不能被其他类继承的类? [复制]
【发布时间】:2016-12-16 16:21:39
【问题描述】:

任何人都可以告诉如何创建类,使其不能被任何其他类继承。

class A {
  public :
          int a;
          int b;
};

class B : class A {
   public :
           int c;
};

在上面的程序中,我不想让其他类被 B 类继承

【问题讨论】:

  • 我不清楚。您只想允许 BA 继承?
  • 您的真正意思是“继承”还是“继承”class B
  • 另外,你为什么要这样做?会造成什么问题?

标签: c++ inheritance


【解决方案1】:

标记班级final(C++11 起):

class A final {
public :
    int a;
    int b;
};

【讨论】:

    【解决方案2】:

    如果您使用的是 C++11 或更高版本,则可以使用 final 关键字,就像提到的其他答案一样。 这应该是推荐的解决方案。

    但是,如果不得不在 C++03 / C++98 中挣扎,您可以将类的构造函数设为private,并使用工厂方法或类创建此类的对象。

    class A {
    private:
        A(int i, int j) : a(i), b(j) {}
        // other constructors.
    
        friend A* create_A(int i, int j);
        // maybe other factory methods.
    };
    
    A* create_A(int i, int j) {
        return new A(i, j);
    }
    // maybe other factory methods.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-16
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多