我很困惑为什么这不起作用.我必须误解QVectors的一些关键...
我创建了一个MCVE来显示问题:
#include <QCoreApplication>
#include <QVector>
struct ChunkRequest
{
ChunkRequest(int x, int z)
{
this->x = x;
this->z = z;
}
int x;
int z;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVector<ChunkRequest> requestedChunks;
requestedChunks.append(ChunkRequest(1, 2));
return a.exec();
}
Run Code Online (Sandbox Code Playgroud)
编译会抛出错误 C2512: 'ChunkRequest' : no appropriate default constructor available
我能够创建一个ChunkRequest变量,ChunkRequest req(1, 2);但是一旦我尝试将它附加到我QVector的错误抛出.
我有理由感到困惑.
编辑:在阅读您的评论之后,我很清楚QVector需要一个默认构造函数来确定数组中每个元素的大小.但这并没有回答为什么.
如果一个struct有一定数量的成员,并且每个成员在内存中都有已知的大小(即使指向动态内存的指针是已知大小),那么我不明白为什么QVector需要一个默认的构造函数?大小应该在编译时知道......对吗?
我有一个B类,它创建一个A类的对象并调用该对象的方法.
啊
#ifndef A_H
#define A_H
class A
{
public:
A(int);
void function();
};
#endif // A_H
Run Code Online (Sandbox Code Playgroud)
a.cpp
#include "a.h"
A::A(int x)
{
}
void A::function(){
//Do something.
}
Run Code Online (Sandbox Code Playgroud)
BH
#ifndef B_H
#define B_H
#include <QVector>
#include <a.h>
class B
{
public:
B(int);
QVector<A> list;
};
#endif // B_H
Run Code Online (Sandbox Code Playgroud)
b.cpp
#include "b.h"
B::B(int y)
{
list.append(A(y));
list[0].function();
}
Run Code Online (Sandbox Code Playgroud)
问题是这不能编译.它返回"没有匹配的函数来调用'A:A()'".我知道这可以通过前向声明来解决,但这在这里不起作用,因为我想调用函数"function".我也不想把全班A都包括在B班.