0

我不明白为什么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();
}
4

1 回答 1

3

向最令人头疼的 parse打个招呼。

StringHandler handler(QString(str));声明一个名为的函数handler,它接受 aQString并返回 a 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++ 最令人头疼的解析

于 2015-10-18T10:48:02.510 回答