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

时间:2020-06-03 17:01:13

标签: c++

下面列出了相关代码。为什么编译器会抱怨“'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

2 个答案:

答案 0 :(得分:3)

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

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

struct B: A
{
    B() : A(10) {}

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

但是您必须将某些东西传递给A的构造函数。

答案 1 :(得分:1)

之所以发生这种情况,是因为继承附带了父子关系。您必须先创建父级,才能创建子级。父类A具有带参数的非默认构造函数。您需要通过其构造函数中的类B调用该构造函数,如下所示:

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