Passing QUrl to a QNetworkRequest constructor caus

2019-05-06 21:06发布

when I'm passing a QUrl to a QNetworkRequest constructor I get strange errors form the compiler. It's even more strange that it happens only in a specific case, here's an example:

#include <QCoreApplication>
#include <QNetworkReply>

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

    QString str;

    QNetworkRequest req(QUrl(str));
    req.setUrl(QUrl(str)); // error: request for member 'setUrl' in 'req', which is of non-class type 'QNetworkRequest ()(QUrl)'

    QNetworkRequest req2(QUrl(QString("http://google.com"))); // works here perfectly!
    req2.setUrl(QUrl(str));

    QNetworkRequest req3;
    req3.setUrl(QUrl(str));

    QUrl url(str);
    QNetworkRequest req4(url);
    req4.setUrl(QUrl(str));

    return a.exec();
}

g++-4.2 is saying:

main.cpp:11: error: request for member 'setUrl' in 'req', which is of non-class type 'QNetworkRequest ()(QUrl)'

vs2010 compiler says:

error C2228: left of '.setUrl' must have class/struct/union

And when I want to pass the "corrupted" QNetworkRequest to a QNetworkAccessManager::get method I get an additional explanation from vs2010:

error C2664: 'QNetworkAccessManager::get' : cannot convert parameter 1 from 'QNetworkRequest (__cdecl *)(QUrl)' to 'const QNetworkRequest &'
      Reason: cannot convert from 'overloaded-function' to 'const QNetworkRequest'
      No constructor could take the source type, or constructor overload resolution was ambiguous

How odd.. anyone have a clue? Maybe I just forgot how to program..

1条回答
来,给爷笑一个
2楼-- · 2019-05-06 21:40

You've encountered a so-called "vexing parse". This:

QNetworkRequest req(QUrl(str));

is equivalent to

QNetworkRequest req(QUrl str);

which is a function declaration.

To declare a variable and initialise it from a temporary, you need

QNetworkRequest req{QUrl{str}};                    // C++11
QNetworkRequest req = QNetworkRequest(QUrl(str));  // Historic C++ (if it's copyable)

or use a named variable rather than a temporary, as you do with req4.

查看更多
登录 后发表回答