我现在正在学习 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 constructor到 ClockOfTheLongNow
,例如:
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/