仅更改函数的特定默认参数

Posted

技术标签:

【中文标题】仅更改函数的特定默认参数【英文标题】:Change only a specific Default Parameter on a function 【发布时间】:2019-03-06 09:52:21 【问题描述】:

我正在使用qt,我正在尝试使用QInputDialog::getText() 函数从用户那里获取输入,从Documentation 函数的定义是:

QString QInputDialog::getText(QWidget * parent, const QString & title, const QString & label, QLineEdit::EchoMode mode = QLineEdit::Normal, const QString & text = QString(), bool * ok = 0, Qt::WindowFlags flags = 0, Qt::InputMethodHints inputMethodHints = Qt::ImhNone)

这是我的代码:

bool ok=0;
newAddress = QInputDialog::getText(0,"Enter an Address to Validate",
                                       "Adress: comma separated (e.g Address line 1, Address line 2, City, Postal Code)"
                                       ,&ok);

但我得到了错误:

error: no matching function for call to 'QInputDialog::getText(int, const char [29], const char [80], bool*)'
                                            ,&ok);
                                                ^

但是当我在 *ok 参数之前传递所有参数时,例如:

bool ok=0;
newAddress = QInputDialog::getText(0,"Enter an Address to Validate",
                                       "Adress: comma separated (e.g Address line 1, Address line 2, City, Postal Code)"
                                       ,QLineEdit::Normal,
                                       QString(),&ok);

它有效。

我真的不明白为什么我不能只更改我想要的默认参数并将其余参数保留为默认值?。

【问题讨论】:

【参考方案1】:

当您为具有默认参数的特定参数传递值时,您必须为它之前的所有默认参数传递值。否则,您传递的值将作为第一个默认参数的值。

所以你必须这样做:

newAddress = QInputDialog::getText(
             0,
             "Enter an Address to Validate",
             "Adress: comma separated (e.g Address line 1, Address line 2, City, Postal Code)", 
             QLineEdit::Normal, 
             QString(), 
             &ok);

bool * 参数后面的参数可以省略传递值。

[dcl.fct.default]/1 中的 C++ 标准状态

默认参数将用于缺少尾随参数的调用。

【讨论】:

当我开始学习编程时,我使用过 Python,它有这个功能,您可以通过名称传递参数。如果他们在 C++ 中有类似的东西,那就太好了。感谢您的回答,我不知道尾随参数问题。【参考方案2】:

在 C++ 中,您只能在参数列表末尾使用(一个或多个)默认参数。如果中间省略参数,编译器无法知道,哪个参数属于哪个参数。因此,您必须在传递&ok 之前手动指定默认参数QLineEdit::Normal and QString()

在您不工作的情况下,编译器会尝试将您的布尔指针匹配到参数列表中的下一个类型,即QLineEdit::EchoMode,因此不兼容。

【讨论】:

【参考方案3】:

错误是因为可选参数:

QString QInputDialog::getText(
    QWidget * parent, 
    const QString & title, 
    const QString & label,
    QLineEdit::EchoMode mode = QLineEdit::Normal, 
    const QString& text = QString(), 
    bool * ok = 0,
    Qt::WindowFlags flags = 0, 
    Qt::InputMethodHints inputMethodHints = Qt::ImhNone)


QInputDialog::getText(
    0,
    "Enter an Address to Validate",
    "Adress: comma separated (e.g Address line 1, Address line 2, City, Postal Code)",
    --> QLineEdit::EchoMode ??  
    --> QString& text ??
    &ok);

如果您设置一个可选参数,则必须将所有可选参数设置在该参数的左侧,在您的情况下为 QLineEdit::EchoMode 和 QString& text

【讨论】:

以上是关于仅更改函数的特定默认参数的主要内容,如果未能解决你的问题,请参考以下文章

Python 3:更改现有函数参数的默认值?

WooCommerce 复合产品:如何使用 URL 参数更改组件的默认产品选项?

PHP:函数参数的动态默认值

函数重载和默认参数

将默认参数定义为全局变量

根据项目特定设置函数默认值 R