没有用于调用默认构造函数的匹配函数

No matching function for call to default constructor

本文关键字:函数 构造函数 默认 用于 调用      更新时间:2023-10-16

下面列出了相关代码。为什么编译器抱怨"'B::B()'被隐式删除,因为默认定义格式不正确"?这是我脑海中的第一个问题。我很快就会找到提示。编译器说:"没有用于调用'A::A()'的匹配函数"。

我的问题是,为什么在 B 类中应该有一个匹配函数来调用"A::A()"。如果能对这个问题有所帮助,我将不胜感激。

#include<iostream>
using namespace std;
struct A
{
int x;
A(int x): x(x) {std::cout << "A:A(int)" <<x << std::endl;} 
};
struct B: A
{
};
int main()
{
B b;
}

错误消息:

<source>: In function 'int main()':
<source>:17:7: error: use of deleted function 'B::B()'
17 |     B b;
|       ^
<source>:11:8: note: 'B::B()' is implicitly deleted because the default definition would be ill-formed:
11 | struct B: A
|        ^
<source>:11:8: error: no matching function for call to 'A::A()'
<source>:8:5: note: candidate: 'A::A(int)'
8 |     A(int x): x(x) {std::cout << "A:A(int x=1)" <<x << std::endl;} // user-defined default constructor
|     ^
<source>:8:5: note:   candidate expects 1 argument, 0 provided
<source>:5:8: note: candidate: 'constexpr A::A(const A&)'
> Blockquote

编译器无法为 B 生成默认构造函数,因为 B 的构造函数需要调用 A 的构造函数。A 的构造函数需要一个 int,而编译器不知道要传递给它什么值。这意味着您需要自己声明一个 B 的构造函数来处理这个问题。

你可以让 B 的构造函数也采用一个 int 并使用它,或者例如让 B 使用固定值:

struct B: A
{
B() : A(10) {}
B(int x) : A(x) {}
};

但是你必须把一些东西传递给 A 的构造函数。

这是因为继承附带的父子关系。如果不创建父项,则无法创建子项。父类A具有采用参数的非默认构造函数。您需要通过构造函数中的类 B 调用该构造函数,如下所示:

struct B: A
{
// example
B() : A(3) {}
};