在构造函数中将std :: string转换为QString

时间:2015-10-18 10:00:26

标签: c++ constructor compiler-errors most-vexing-parse

我无法理解为什么std::string在将其传递给构造函数时转换为QString。这是一个小例子:

  class StringHandler
 {
 private:
     QString str;
 public:
     StringHandler(QString s): str(s) {}
  };

 int main(int argc, char *argv[])
 {
    QCoreApplication a(argc, argv);

    std::string str = "string";
    QString qstr(str); // it gives error there are no constructor QString(std::string)
    StringHandler handler(QString(str));//it does not give an error. Why?

    return a.exec();
 }

修改

class StringHandler
{
public:
    StringHandler(QString s): str(s) {}
    QString str;
};

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

std::string str = "string";
StringHandler handler(QString(str));//Here should be error, but there no error. Why?
qDebug()<<handler.str; //Error is here: request for member 'str' in 'handler', which is of non-class type 'StringHandler(QString)'

return a.exec();
}

1 个答案:

答案 0 :(得分:3)

most vexing parse打个招呼。

StringHandler handler(QString(str));声明一个名为handler的函数,它接受QString并返回StringHandler。是。感谢C ++解析规则。

现在错误消息request for member 'str' in 'handler', which is of non-class type 'StringHandler(QString)'有意义:handler被视为类型为StringHandler(QString)的函数,并且您正试图访问名为str的成员在其中,但当然函数没有成员,因此编译失败。

您可以使用统一初始化语法来解决此问题:

StringHandler handler{QString(str)};

上述内容无法解析为函数声明,因此编译应该因预期的原因而失败:没有匹配的构造函数QString(std::string)

有关详细信息,请参阅C++'s most vexing parse again