c++ - 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.
解决方案
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;
};
推荐阅读
- c - 超过 9 皇后问题的分段错误
- linux - 内存100%满了,postgresql服务没有启动,这种情况怎么办?
- c# - 无法让控件适用于我的俄罗斯方块游戏
- excel - 按标题名称复制列并粘贴到另一个工作簿
- reporting-services - SSRS - 如何在主报表中创建动态子报表
- php - 将内容而不是变量传递给 PHP 函数
- symfony - 传递给 App\Entity\Invitacion::setEmail() 的参数 1 必须是 App\Entity\User 的实例或 null - Symfony 4
- javascript - 尝试渲染从弹性搜索接收到的 JSON 字典但得到 [object Promise] 错误
- php - PHP将单词的第一个字母大写
- laravel - 在 DatabaseSeeder.php 的调用函数中注释时,Laravel 数据库 FooSeeder 仍在播种