c++ - 如何修复 C++ 中的 "no instance of constructor matches argument list"错误?

标签 c++

我现在正在学习 C++,正在编写一个使用成员初始值设定项列表的程序。这是我正在使用的代码:

#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();
}

我收到的错误来自这里的这一行,其中显示 apert{year_of_apert }:

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

我得到的错误是这样的:

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

我已经尝试寻找问题的解决方案,但到目前为止,还没有成功。预期的输出应该是这样的:

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

最佳答案

ClockOfTheLongNow 没有采用 long (或任何其他类型的值)作为输入的构造函数,但您正在尝试构造 apert 成员,将 year_of_apert 传递给其构造函数。

您需要添加 converting constructorClockOfTheLongNow,例如:

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

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

    ...
private:
    int year;
};

或者,您可以更改现有的 default constructor给它一个默认参数值,以便它也可以充当转换构造函数,例如:

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

关于c++ - 如何修复 C++ 中的 "no instance of constructor matches argument list"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60607622/

相关文章:

c++ - 如何根据对象是否为右值引用路由到不同的实现?

C++,MingW,对 `libiconv' 的 undefined reference

c++ - 如何用 C++ 像 Java 一样表达匿名方法重写?

C++ sizeof() 没有返回正确的大小

c++ 运算符必须是非静态成员函数

c++ 从标准输入快速读写

c++ - 在巴比伦算法中为 C++ 中的平方根获取无限循环

c++ - #include <文件名> 和 #include "filename"有什么区别?

c++ - C++ 中的 native isnan 检查

c++ - 可以在构造函数中创建 Pthreads 吗?