使用QVector时,没有对默认构造函数的匹配调用 [英] No matching call to default constructor, when using QVector
问题描述
我有一个B类,它创建A类的对象并调用该对象的方法。
I have a class B that creates an object of a class A and calls a method of the object.
ah
#ifndef A_H
#define A_H
class A
{
public:
A(int);
void function();
};
#endif // A_H
a.cpp
#include "a.h"
A::A(int x)
{
}
void A::function(){
//Do something.
}
bh
#ifndef B_H
#define B_H
#include <QVector>
#include <a.h>
class B
{
public:
B(int);
QVector<A> list;
};
#endif // B_H
b.cpp
#include "b.h"
B::B(int y)
{
list.append(A(y));
list[0].function();
}
问题是它不能编译。它返回没有匹配的函数调用'A:A()'。我知道可以使用前向声明解决此问题,但这在这里不起作用,因为我想将函数称为函数。我也不想将整个A类都包含在B类中。
The problem is that this does not compile. It returns "no matching function to call 'A:A()'". I know that this can be solved with a forward declaration but this does not work here since I want to call the function "function". I also do not want to include the whole class A in the class B.
推荐答案
与许多Qt容器一样, QVector
的元素类型必须为您的版本中的可分配数据类型 。
As with many Qt containers, QVector
's element type must be an assignable data type in your version.
与标准库不同, Qt将此定义为:
存储在各个容器中的值可以是任何可分配的数据类型。要获得资格,类型必须提供默认的构造函数,副本构造函数和赋值运算符。
The values stored in the various containers can be of any assignable data type. To qualify, a type must provide a default constructor, a copy constructor, and an assignment operator.
这真的很不幸,因为< a href = https://stackoverflow.com/q/33380402/560648>在您的示例中,实际上不需要默认的构造函数,实际上不需要 std :: vector
可以(合规地)使用没有元素的元素类型。
This is really unfortunate, because there's no practical need for a default constructor in your example, and indeed a std::vector
would (compliantly) let you use an element type that doesn't have one.
QVector :: value(int )
函数确实依赖此属性,但您没有使用它! Qt开发人员必须预先进行某种检查,而不是采用标准库的方法仅在实际需要时检查先决条件,否则这是代码的意外!
The QVector::value(int)
function does rely on this property, but you're not using it! The Qt devs must be doing some kind of checks up-front, rather than taking the standard library's approach of "just check preconditions when they're actually needed", or else this is an "accident" of the code!
因此,直到更改此参数的5.13 ,您必须为 A
提供默认的构造函数,抱歉。
As a consequence, until 5.13 in which this was changed, you will have to give A
a default constructor, sorry.
也不要忘记复制构造函数…以及对该 A :: function()
定义的适当限定。
Don't forget a copy constructor, too… and a proper qualification on that A::function()
definition.
前向声明不能解决这个问题,您也不需要一个。实际上,在此特定程序中添加一个实际上不会执行任何操作。 ;)
A forward declaration will not solve this, neither do you need one. In fact, adding one to this particular program will do literally nothing. ;)
这篇关于使用QVector时,没有对默认构造函数的匹配调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!