C++ 具有具有参数的自定义对象的QVector?

C++ 具有具有参数的自定义对象的QVector?,c++,qt,vector,qvector,C++,Qt,Vector,Qvector,我正在尝试将QVector与名为RoutineItem的自定义对象一起使用 但给出了这个错误: C:\Qt\5.2.1\mingw48_32\include\QtCore\qvector.h:265: error: no matching function for call to 'RoutineItem::RoutineItem()' 这是RoutineItem构造函数: RoutineItem(QString Name,int Position,int Time,bool hasCount

我正在尝试将QVector与名为RoutineItem的自定义对象一起使用

但给出了这个错误:

C:\Qt\5.2.1\mingw48_32\include\QtCore\qvector.h:265: error: no matching function for call to 'RoutineItem::RoutineItem()'
这是RoutineItem构造函数:

RoutineItem(QString Name,int Position,int Time,bool hasCountdown = false,bool fastNext = false);
如果我删除了所有构造函数参数,我就不会再得到那个错误。
如何将QVector与具有参数的自定义对象一起使用?

问题在于QVector要求元素具有默认构造函数(这是有关的错误消息)。您可以在类中定义一个。例如:

class RoutineItem {
    RoutineItem(QString Name, int Position,
                int Time, bool hasCountdown = false,
                bool fastNext = false);
    RoutineItem();
    [..]
};
或者,您可以让所有参数都具有默认值:

class RoutineItem {
    RoutineItem(QString Name = QString(), int Position = 0,
                int Time = 0, bool hasCountdown = false,
                bool fastNext = false);
    [..]
};
或者,您可以构造RoutineItem的默认值并使用它初始化所有向量项:

RoutineItem item("Item", 0, 0);
// Create a vector of 10 elements and initialize them with `item` value
QVector<RoutineItem> vector(10, item);
RoutineItem项目(“项目”,0,0);
//创建一个包含10个元素的向量,并用'item'值初始化它们
QVector(10项);

在中提供非默认参数

示例:下面创建10个
RoutineItem
元素,这些元素具有相同的
名称
位置
时间

QVector<RoutineItem> foo(10, RoutineItem("name", 123, 100 ));
                                            ^     ^     ^
                                            |     |     |
                                            +-----+-----+-----Provide arguments
qvectorfoo(10,RoutineItem(“name”,123100));
^     ^     ^
|     |     |
+-----+-----+-----提供论据

如果您愿意使用C++11和
std::vector
,则对默认可构造性没有更多要求:

void test()
{
   class C {
   public:
      explicit C(int) {}
   };

   std::vector<C> v;
   v.push_back(C(1));
   v.push_back(C(2));
}
void测试()
{
C类{
公众:
显式C(int){}
};
std::向量v;
v、 推回(C(1));
v、 推回(C(2));
}

这段代码在C++11之前不起作用,它也不适用于
QVector

和标准容器一样,您需要为QVector提供一个默认的可构造类型。@πάνταῥεῖ C++11标准容器不需要默认的可构造项。项目上的要求位置特定于您如何使用容器。例如,
std::list
甚至不需要复制可构造的项,如果您可以坚持使用
emplace
而不是
push
方法。可能会重复