我想约束派生类必须有一个默认构造函数。 我目前正在以一种变态的方式思考它
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/