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



我现在正在学习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_part}:

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(或任何其他类型的值(为输入的构造函数,但您正试图通过将year_of_apert传递给其构造函数来构造apert成员。

您需要添加一个转换构造函数ClockOfTheLongNow,例如:

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

或者,您可以更改现有的默认构造函数,为其提供默认参数值,使其也可以作为转换构造函数

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

错误告诉您,参数中给定的类型不存在构造函数。

Avout构造函数提供一个类型为long的参数,然后在apert变量中初始化ClockOfTheLongNow类型的构造函数。

换句话说,你必须为你的时钟结构创建一个新的构造函数,它看起来像这样:

ClockOfTheLongNow(long parameterYear) { 
year = parameterYear;
}

相关内容

最新更新