首页 > 解决方案 > How to fix an "no instance of constructor matches argument list" error in C++?

问题描述

I am learning C++ right now and I am writing a program that utilizes member initializer list. Here is the code that I am working with:

#include <cstdio>

struct ClockOfTheLongNow {
    ClockOfTheLongNow() { 
        year = 2019;
    }
    void add_year() {
        year++;
    }
    bool set_year(int new_year) { 
        if (new_year < 2019) return false;
        year = new_year;
        return true;
    }
    int get_year() const { 
        return year;
    }
private:
    int year;
};

struct Avout{
    Avout(const char* name, long year_of_apert) : name{ name }, apert{ year_of_apert } {

    }
    void announce() const {
        printf("My name is %s and my next apert is %d.\n", name, apert.get_year());
    }
    const char* name;
    ClockOfTheLongNow apert;
};

int main() {
    Avout raz{ "Eramas", 3010 }; 
    Avout jad{ "Jad", 4000 };
    raz.announce();
    jad.announce();
}

The error that I am getting is coming from this line here where it says apert{ year_of_apert }:

Avout(const char* name, long year_of_apert) : name{ name }, apert{ year_of_apert } {

The error that I am getting back is this:

no instance of constructor "ClockOfTheLongNow::ClockOfTheLongNow" matches the argument list -- argument types are: (long)

I have already tried to look up solutions to the problem but, so far, have had no luck. The expected output is supposed to be this:

My name is Erasmas and my next apert is 3010.
My name is Jad and my next apert is 4000.

标签: c++

解决方案


ClockOfTheLongNow does not have a constructor that takes a long (or any other kind of value) as input, but you are trying to construct the apert member by passing year_of_apert to its constructor.

You need to add a converting constructor to ClockOfTheLongNow, eg:

struct ClockOfTheLongNow {
    ClockOfTheLongNow() { // <-- default constructor
        year = 2019;
    }

    ClockOfTheLongNow(int theYear) { // <-- add a converting constructor
        year = theYear;
    }

    ...
private:
    int year;
};

Alternatively, you can change your existing default constructor to give it a default parameter value so it can act as a converting constructor as well, eg:

struct ClockOfTheLongNow {
    ClockOfTheLongNow(int theYear = 2019) { // <-- default + converting constructor
        year = theYear;
    }
    ...
private:
    int year;
};

推荐阅读