You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调整vector大小时出现“no matching constructor”错误求助

Fixing the "no matching constructor" Error When Resizing a Vector of 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 string and double
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:47:05