以Qt框架的以下文档为例,即使我的问题不是Qt特定的:
https://doc.qt.io/qt-5/qversionnumber.html
您可以找到静态公共成员函数:
QVersionNumber fromString(const QString &string, int *suffixIndex = nullptr)
代替:
QVersionNumber(const QString &string, int *suffixIndex = nullptr)
在构造函数列表中。
我已经看到在许多库API中做出的这种选择,我无法理解它的优点是什么以及缺少该构造函数的原因。
这实际上是一个很好的问题。
原因因情景而异,但涉及以下问题:
以上所有都将涉及一定程度的主观性。
假设的例子,猜测QVersionNumber的内部,
你会如何在初始化列表中写这个?
QVersionNumber
QVersionNumber::fromString(const QString &string, int *suffixIndex)
{
std::optional<QVersionNumber> result;
auto first = string.begin();
auto last = string.end();
auto opt_major = maybe_extract_decimal(first, last); // modifies first
if (not opt_major.has_value())
result.emplace();
else
{
auto opt_minor = maybe_extract_decimal(first, last); // modifies first
if (not opt_major.has_value())
result.emplace(*opt_major);
else
result.emplace(*opt_minor);
}
if (suffixIndex)
*suffixIndex = int(std::difference(string.begin(), first);
return *std::move(result);
}
这当然是可能的,推迟到一个私有构造函数,它接受一个专门的函数对象。但是图书馆的作者可能认为这太过神秘或难以维护。
静态创建方法很方便,因为它们不需要创建冗余对象,可以添加到它们创建的对象的代码中。使用创建方法insteed构造函数的原因有很多。这里仅仅是少数:
nullptr
或某些“错误”对象类型。fromString
在构造函数调用之前解析字符串参数。我建议你熟悉设计模式,尤其是сreational pattern。