当我将 QUrl 传递给 QNetworkRequest 构造函数时,我从编译器中收到奇怪的错误。更奇怪的是,它只发生在特定情况下,这是一个例子:
#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 说:
main.cpp:11: error: request for member 'setUrl' in 'req', which is of non-class type 'QNetworkRequest ()(QUrl)'
vs2010 编译器说:
error C2228: left of '.setUrl' must have class/struct/union
当我想将“损坏的” QNetworkRequest 传递给 QNetworkAccessManager::get 方法时,我从 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
多奇怪..有人有线索吗?也许我只是忘记了如何编程..
最佳答案
您遇到了所谓的“恼人的解析”。这:
QNetworkRequest req(QUrl(str));
相当于
QNetworkRequest req(QUrl str);
这是一个函数声明。
要声明变量并从临时变量初始化它,您需要
QNetworkRequest req{QUrl{str}}; // C++11
QNetworkRequest req = QNetworkRequest(QUrl(str)); // Historic C++ (if it's copyable)
或者使用命名变量而不是临时变量,就像使用
req4
一样。关于c++ - 将 QUrl 传递给 QNetworkRequest 构造函数会导致 "non-class type"编译器错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19690650/