这个问题在这里已经有了答案:
no default constructor exists for class x (inheritance) C++
(2 个回答)
1年前关闭。
相关代码如下。为什么编译器会报错“'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 的构造函数。
关于c++ - 调用默认构造函数没有匹配的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62178475/