[英]QVector with custom objects that have arguments?
I`m trying to use a QVector with a custom object named RoutineItem. 我正在尝试将QVector与名为RoutineItem的自定义对象一起使用。
But this error is given: 但是给出了这个错误:
C:\Qt\5.2.1\mingw48_32\include\QtCore\qvector.h:265: error: no matching function for call to 'RoutineItem::RoutineItem()'
This is the RoutineItem constructor: 这是RoutineItem构造函数:
RoutineItem(QString Name,int Position,int Time,bool hasCountdown = false,bool fastNext = false);
If I remove all the constructor arguments I no longer get that error. 如果删除所有构造函数参数,则不会再出现该错误。 How can I use QVector with a custom object that has arguments? 如何将QVector与具有参数的自定义对象一起使用?
The problem is that QVector requires that the element has a default constructor (that is the error message about). 问题在于QVector要求元素具有默认构造函数(即有关该错误的消息)。 You can define one in your class. 您可以在课堂上定义一个。 For example: 例如:
class RoutineItem {
RoutineItem(QString Name, int Position,
int Time, bool hasCountdown = false,
bool fastNext = false);
RoutineItem();
[..]
};
Alternatively, you can let all arguments have a default values: 或者,可以让所有参数都具有默认值:
class RoutineItem {
RoutineItem(QString Name = QString(), int Position = 0,
int Time = 0, bool hasCountdown = false,
bool fastNext = false);
[..]
};
Alternatively, you can construct a default value of RoutineItem and initialize all vector items by it: 另外,您可以构造默认值RoutineItem并通过它初始化所有矢量项:
RoutineItem item("Item", 0, 0);
// Create a vector of 10 elements and initialize them with `item` value
QVector<RoutineItem> vector(10, item);
Provide the non-default arguments in QVector constructor 在QVector构造函数中提供非默认参数
Example: following creates 10 RoutineItem
elements with same Name
, Position
, Time
示例:以下创建具有相同Name
, Position
, Time
10个RoutineItem
元素
QVector<RoutineItem> foo(10, RoutineItem("name", 123, 100 ));
^ ^ ^
| | |
+-----+-----+-----Provide arguments
If you're willing to use C++11 and std::vector
, there's no more requirement for default-constructability: 如果您愿意使用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));
}
This code won't work pre-C++11, and it won't work with QVector
. 此代码在C ++ 11之前不起作用,并且在QVector
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.