我试图从基类继承构造函数,并在派生类中定义其他构造函数。

#include <iostream>

#define BREAK_THIS_CODE 1

class Base
{
public:
    Base()
    {
        std::cout << "Base " << "\n";
    }

    Base(int i)
    {
        std::cout << "Base " << i << "\n";
    }
};

class Derived : public Base
{
public:
    using Base::Base;

#if BREAK_THIS_CODE
    Derived(int i, int j)
    {
        std::cout << "Derived " << i << " " << j << "\n";
    }
#endif
};

int main()
{
    Derived d1(10);
    Derived d2; // error C2512: 'Derived': no appropriate default constructor available

    return 0;
}

添加Derived(int, int)似乎会删除Base(),但是Base(int)不受此影响。为什么要删除默认构造函数?我期望Derived总共有三个用户定义的构造函数。我唯一能想到的是,继承的Base()构造函数被视为隐式声明的默认构造函数,添加额外的构造函数将删除默认构造函数。

我已经在VS2015上尝试过此操作,并收到以下错误:
1>  main.cpp
1>main.cpp(37): error C2512: 'Derived': no appropriate default constructor available
1>  main.cpp(19): note: see declaration of 'Derived'

还对Coliru尝试了以下示例:http://coliru.stacked-crooked.com/a/790b540c44dccb9f
clang++ -std=c++11 -O3 -pedantic -pthread main.cpp && ./a.out
main.cpp:35:10: error: no matching constructor for initialization of 'Derived'
        Derived d2;
                ^
main.cpp:22:14: note: candidate constructor (inherited) not viable: requires 1 argument, but 0 were provided
        using Base::Base;
                    ^
main.cpp:13:2: note: inherited from here
        Base(int i)
        ^
main.cpp:19:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
class Derived : public Base
      ^
main.cpp:19:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided
main.cpp:25:2: note: candidate constructor not viable: requires 2 arguments, but 0 were provided
        Derived(int i, int j)
        ^
1 error generated.

最佳答案

CppReference:



因此,您不能继承默认的构造函数。当一个类声明了用户定义的构造函数时,编译器不会为该类生成默认的构造函数,除非您使用Derived() = default明确要求一个构造函数。当您删除用户定义的构造函数时,编译器可以为您生成一个默认的构造函数。

关于c++ - 使用关键字继承构造函数时发生意外行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41045959/

10-11 23:10
查看更多