调整vector大小时出现“no matching constructor”错误求助
Foo Hey there, let's break down why you're hitting this error and how to fix it step by step.
First, Fix the Incomplete Copy Constructor
Looking at your code, your copy constructor definition is cut off and has a syntax error:
Foo::Foo( const Foo& other) { name_ = other.name(); score_ = other.score(...
You need to complete the call to score() and close the function. A cleaner, more efficient version using an initializer list (instead of in-body assignment) would be:
Foo::Foo(const Foo& other) : name_(other.name()), score_(other.score()) {}
Root Cause of the Resize Error
The main issue triggering the "no matching constructor" error during vector resizing is that your Foo class lacks a default constructor (a constructor that takes no parameters).
When you call vector::resize() without providing a pre-made element to copy, the vector needs to create new Foo objects from scratch. To do this, it looks for a default constructor (Foo()), but your class only defines:
- A constructor that takes a
stringanddouble - A copy constructor
- A move constructor
Since the compiler can't find a matching default constructor, it throws the error you're seeing.
Solutions
You have two solid options to fix this:
Option 1: Add a Default Constructor
You can explicitly define a default constructor, either with custom initial values or let the compiler generate one for you:
Custom Default Constructor
class Foo { public: // Add this default constructor Foo() : name_(""), score_(0.0) {} // ... rest of your existing constructors and methods };
Use Compiler-Generated Default Constructor (C++11+)
If you just want the compiler to generate a default constructor that default-initializes your members, use:
class Foo { public: // Add this line to use compiler-generated default constructor Foo() = default; // ... rest of your existing constructors and methods };
Option 2: Resize with a Pre-Defined Foo Object
If you don't want to add a default constructor, you can pass an existing Foo instance to resize(). The vector will use the copy constructor to create new elements based on this instance:
#include <vector> int main() { std::vector<Foo> fooVector; Foo defaultFoo("Default Name", 0.0); // Resize to 5 elements, all copies of defaultFoo fooVector.resize(5, defaultFoo); return 0; }
Either of these approaches will resolve the "no matching constructor" error when resizing your vector.
内容的提问来源于stack exchange,提问作者Lin Ma

