QVector存储自定义结构体编译报错:无合适默认构造函数
Hey there! Let's break down why your code is throwing that error and how to fix it quickly.
Why the Error Happens
The root issue here is that older versions of Qt (like Qt 4) require elements stored in QVector to have a default constructor (a constructor that takes no arguments). Even though you're trying to append a pre-constructed ChunkRequest object, the QVector implementation in older Qt versions needs to default-construct elements when it allocates or resizes its internal buffer.
Your ChunkRequest struct only has a constructor that takes two int parameters—no default constructor exists, so the compiler can't satisfy QVector's requirement.
Solutions
Here are three straightforward ways to fix this:
1. Add a Default Constructor to ChunkRequest
You can explicitly add a default constructor, either using C++11's = default syntax (clean and simple) or a constructor with default parameters:
struct ChunkRequest { // Option 1: Explicit default constructor (C++11+) ChunkRequest() = default; ChunkRequest(int x, int z) { this->x = x; this->z = z; } int x; int z; };
Or, if you prefer, combine it with your existing constructor by setting default values for the parameters:
struct ChunkRequest { // Option 2: Constructor with default parameters ChunkRequest(int x = 0, int z = 0) { this->x = x; this->z = z; } int x; int z; };
2. Use emplace_back() Instead of append()
If you're using Qt 5 or newer, you can use QVector::emplace_back() to construct the ChunkRequest directly inside the vector, which avoids the need for a default constructor. This is more efficient too, since it skips creating a temporary object:
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QVector<ChunkRequest> requestedChunks; // Use emplace_back to construct the object in-place requestedChunks.emplace_back(1, 2); return a.exec(); }
3. Upgrade to Qt 5 or Newer
Qt 5 removed the requirement for container elements to have a default constructor. If you're still on Qt 4, upgrading will let your original code work (or work with emplace_back() as above) without modifying the struct.
Testing the Fix
Whichever solution you pick, your code should now compile without the "no appropriate default constructor available" error. For example, using the default constructor approach, your append() call will work as intended because QVector can now default-construct elements when needed.
内容的提问来源于stack exchange,提问作者mrg95




