QVector与自定义对象有参数?

Sco*_*ott 1 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()'
Run Code Online (Sandbox Code Playgroud)

这是RoutineItem构造函数:

RoutineItem(QString Name,int Position,int Time,bool hasCountdown = false,bool fastNext = false);
Run Code Online (Sandbox Code Playgroud)

如果我删除所有构造函数参数,我不再得到该错误.如何将QVector与具有参数的自定义对象一起使用?

vah*_*cho 6

问题是QVector要求元素有一个默认构造函数(即有关的错误消息).您可以在班级中定义一个.例如:

class RoutineItem {
    RoutineItem(QString Name, int Position,
                int Time, bool hasCountdown = false,
                bool fastNext = false);
    RoutineItem();
    [..]
};
Run Code Online (Sandbox Code Playgroud)

或者,您可以让所有参数都具有默认值:

class RoutineItem {
    RoutineItem(QString Name = QString(), int Position = 0,
                int Time = 0, bool hasCountdown = false,
                bool fastNext = false);
    [..]
};
Run Code Online (Sandbox Code Playgroud)

或者,您可以构造一个默认值RoutineItem并通过它初始化所有矢量项:

RoutineItem item("Item", 0, 0);
// Create a vector of 10 elements and initialize them with `item` value
QVector<RoutineItem> vector(10, item);
Run Code Online (Sandbox Code Playgroud)