没有用于调用默认构造函数的匹配函数
No matching function for call to default constructor
下面列出了相关代码。为什么编译器抱怨"'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) {}
};
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- makefile对我的名称空间对象/函数/构造函数的不确定引用
- 没有可调用的匹配函数(构造函数),候选函数不同于对给定类型的引用
- C++库制作,隐藏在标头中没有友元的析构函数/构造函数
- 从另一个成员函数/构造函数调用C++构造函数是否执行初始值设定项列表
- 在另一个函数/构造函数 [C++] 中初始化后使变量只读
- std::调用函数时找不到函数构造函数
- 显式调用基类析构函数/构造函数合法吗
- 函数构造函数和nullptr
- 用委托构造函数构造函数
- 虚函数构造函数和调用虚函数时会发生什么
- 一些Qt函数/构造函数参数的内存管理
- 使用for_each或std::transform时,c++函函数构造函数是如何被调用的?
- std函数构造函数初始化