带有可选参数的构造函数

问题描述 投票:0回答:1

我在Qt中创建了QLineEdit的子类,我想让用户在初始化/创建控件时能够设置一些可选参数。我知道这是以我定义窗口小部件的构造函数的方式处理的。

但是我想使这些参数可选,所以如果用户决定不定义它们,构造函数将使用我设置的默认值。例如,如果用户未在下面的代码中的构造函数中定义PathMode,则默认为LineEditPath::PathMode::ExistingFile。我不知道该怎么做。

如果正确的方法是拥有多个构造函数,我就可以了。在每个构造函数中都有初始化列表似乎是多余的。

这是我目前的代码:

。H

class LineEditPath : public QLineEdit
{
    ...
    explicit LineEditPath(QWidget *parent = nullptr);
    explicit LineEditPath(PathMode pathMode, QWidget *parent = nullptr);
    ...
}

CPP

LineEditPath::LineEditPath(QWidget *parent) : QLineEdit(parent),
    button(new QPushButton("...", this)),
    dialog(new QFileDialog(this)),
    defaultDir(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)),
    m_pathMode(ExistingFile)
{
    init();
}

LineEditPath::LineEditPath(LineEditPath::PathMode, QWidget *parent) : QLineEdit(parent),
    button(new QPushButton("...", this)),
    dialog(new QFileDialog(this)),
    defaultDir(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)),
    m_pathMode(ExistingFile)
{
    init();
    // Additional stuff for this constructor...
}

我需要有多个构造函数,或者我可以只有一个构造函数,并以某种方式设置默认值?

c++ qt
1个回答
1
投票

对于这种情况,也只是给pathmode一个默认值

class LineEditPath : public QLineEdit
{
    ...
    explicit LineEditPath(PathMode pathMode = default_or_sentinel_value, QWidget *parent = nullptr);
    ...
}

并删除其他构造函数。现在,默认值和标记值之间的差异将是您将使用的默认值,而不关心它是由用户提供还是由编译器提供为默认值。我想这可能就是你想要的。

Sentinel值将是特殊值,例如某些“null”值,不能像其他值一样使用。你会有类似if(pathMode.isNull()) {...handle special case...} else {...use pathMode...}的东西来正确处理它。

对于更复杂的情况,您可能需要查看delegating constructors(从FrançoisAndrieux的评论中复制的链接)。

© www.soinside.com 2019 - 2024. All rights reserved.