【发布时间】:2019-06-12 05:52:28
【问题描述】:
我无法编译以下内容:
#include <QVector>
#include <QDebug>
#include <vector>
class item
{
int var;
public:
//Without default constructor this program will not compile
//item(){}
item(int value)
{
var = value;
}
int getVar()
{
return var;
}
};
int main()
{
//This code will not compile
QVector<item> y;
y.append(item(1));
qDebug() << y[0].getVar();
//std::vector however will work despite an absence of a default contructor
std::vector<item> z;
z.push_back(item(1));
qDebug() << z.at(0).getVar();
return 0;
}
确切地说,追加行不会编译。
在这种情况下,为什么 item 必须有一个默认构造函数?
【问题讨论】:
-
可能让
QVector::resize能够默认构造items。 -
@user4581301 但同样的事情也应该适用于
std::vector。对吗? -
@KunalPuri 好点。我需要关闭 C++11 并检查一下。
-
vector仅在您使用resize或类似的强制默认构造时才会抱怨。QVector可能在幕后发生了更多事情。我将不得不把这个留给对 QT 更熟悉的人。