gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:23:39 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com