代码之家  ›  专栏  ›  技术社区  ›  Neel Basu

约束派生类必须具有默认构造函数

  •  1
  • Neel Basu  · 技术社区  · 14 年前

    我想约束派生类必须有一个默认的构造函数。 我现在认为这是反常的

    template <typename Derived>
    class Base{
      public:
        Base(){
    
        }
        virtual ~Base(){
          new Derived;
        }
    };
    

    另一个想法是保持一个没有参数的纯虚拟create()方法。

    但是还有别的办法吗?除了这两个。 我正在用C++的方式思考。但是在PHP中有什么方法可以做到这一点吗(我希望得到否定的答案lol)

    1 回复  |  直到 14 年前
        1
  •  1
  •   Artefacto    14 年前

    是的,在php lol中有一种方法:

    abstract class Base {
        public final function __construct() {
            $this->constructImpl();
        }
        abstract protected function constructImpl();
    }
    
    class Derived extends Base {
        protected function constructImpl() {
            /* implementation here */
        }
    }
    

    基本上,您只需要将构造函数标记为final。