使用 QVector 时,没有对默认构造函数的匹配调用

No matching call to default constructor, when using QVector

我有一个 class B,它创建一个 class A 的对象并调用该对象的方法。

a.h

#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.
}

b.h

#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();
}  

问题是这无法编译。它returns"no matching function to call 'A:A()'"。我知道这可以通过前向声明来解决,但这在这里不起作用,因为我想调用函数 "function"。我也不想在 class B.

中包含整个 class A

首先在a.cpp更新函数定义:

void A::function(){  // A: added
    //Do something.
}

其次,我会添加 A(const A&) 复制构造函数,因为列表可能需要它来进行内部缓冲区重新分配。

与许多 Qt 容器一样,QVector's element type must be an assignable data type 在您的版本中。

不同于标准库,Qt defines this as:

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.

这真的很不幸,因为 there's no practical need for a default constructor in your example,实际上 std::vector 会(顺从地)让您使用没有元素类型的元素类型。

QVector::value(int) 函数确实依赖于此 属性,但您没有使用它! Qt 开发人员必须预先进行某种检查,而不是采用标准库的 "just check preconditions when they're actually needed" 方法,否则这是代码的 "accident"!

因此,until 5.13 in which this was changed你必须给A一个默认构造函数,抱歉。

也不要忘记复制构造函数……以及对该 A::function() 定义的适当限定。

前向声明不会解决这个问题,您也不需要。事实上,将一个添加到这个特定程序实际上什么也做不了。 ;)