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

如何使类完全不可派生。有什么办法吗?

  •  0
  • Hara  · 技术社区  · 15 年前

    嗨,有人告诉我如何使类完全不可派生。有什么办法吗? 请告诉我。 当做 哈拉

    4 回复  |  直到 7 年前
        1
  •  6
  •   Jamison Dance    7 年前

    this 解释如何做,为什么它可能不是一个好主意,由Bjarne Stroustrup(创造者的C++本身)。

        2
  •  4
  •   Mark Rushakoff    15 年前

    如果您的类有一个私有的构造函数,则无法实例化派生类。

    参见 "How can I set up my class so it won't be inherited from?" 关于C++ FAQ Lite。

        3
  •  3
  •   dirkgently    15 年前

    将ctor设为私有。

    class not_derivable { private: not_derivable(){} };
    
    class derived : public not_derivable {};
    
    int main() { derived d; // diagnostic }
    

    或者Dor:

    class not_derivable { private: ~not_derivable(){} };
    
    class derived : public not_derivable {};
    
    int main() { not_derivable *nd = new not_derivable; derived d; //diagnostic }
    
        4
  •  2
  •   David Block    15 年前

    将构造函数设为私有。