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

标签 php c++

我想约束派生类必须有一个默认构造函数。 我目前正在以一种变态的方式思考它

template <typename Derived>
class Base{
  public:
    Base(){

    }
    virtual ~Base(){
      new Derived;
    }
};

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

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

最佳答案

是的,在 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。

关于php - 约束 - 派生类必须具有默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3591694/

相关文章:

PHP 和 字符编码问题

php - preg_替换整个单词

php - 根据用户输入按行回显表

c++ - shared_ptr 赋值符号隐式转换

c++ - 如何像类一样为 std::function 实现类型橡皮擦?

php - PHP 可以检测图像是否为 "Too Light' 吗?

php - 生成子进程的核心转储文件

c++ - boost 线程 : threads or processes?

c++ - ZeroMQ python 到 c++ Pub/Sub

c++ - 使用accumulate方法但不能第一个元素总是显示为0