构造函数继承和自定义构造函数

Constructor inheritance and custom constructors

本文关键字:构造函数 自定义 继承      更新时间:2023-10-16

使用这个层次结构:

struct TestBase {
    // Constructor
    TestBase();
    TestBase(int a);
    TestBase(TestBase const &testBase);
    // Destructor
    virtual ~TestBase();
};
struct TestChild : public TestBase {
    // Constructor inheritance
    using TestBase::TestBase;
};

使用下面的测试代码:

TestBase testBase;                  // 1) Custom constructor
TestChild testChild;                // 2) Default constructor created by the compiler
TestChild testChild2(1);            // 3) Inherited from parent with 'using' keyword
TestChild testChild3(testChild);    // 4) Default copy constructor created by the compiler ?
TestChild testChild4(testBase);     // 5) Doesn't work, why it doesn't inherit ?

首先,我认为在测试4复制构造函数是从TestBase继承的(通过'using'关键字),但事实上,这是因为编译器生成一个默认的复制构造函数调用父类的复制构造函数,它是正确的吗?

复制构造函数不能被继承,因为它必须具有与类相同的参数类型,这也是正确的吗?

但是为什么测试5不能编译?它不是TestChild类的复制构造函数,所以它必须被继承,不是吗?


这是错误信息:

foo.cpp: In function ‘int main()’:
foo.cpp:21:34: error: no matching function for call to ‘TestChild::TestChild(TestBase&)’
 TestChild testChild4(testBase);     // 5) Doesn't work, why it doesn't inherit ?
                              ^
foo.cpp:21:34: note: candidates are:
foo.cpp:11:12: note: TestChild::TestChild()
     struct TestChild : public TestBase {
            ^
foo.cpp:11:12: note:   candidate expects 0 arguments, 1 provided
foo.cpp:13:25: note: TestChild::TestChild(int)
         using TestBase::TestBase;
                         ^
foo.cpp:13:25: note:   no known conversion for argument 1 from ‘TestBase’ to ‘int’
foo.cpp:11:12: note: TestChild::TestChild(const TestChild&)
     struct TestChild : public TestBase {
            ^
foo.cpp:11:12: note:   no known conversion for argument 1 from ‘TestBase’ to ‘const TestChild&’
foo.cpp:11:12: note: TestChild::TestChild(TestChild&&)
foo.cpp:11:12: note:   no known conversion for argument 1 from ‘TestBase’ to ‘TestChild&&’

为构造函数命名的using-declaration隐式声明了一组继承的构造函数,但值得注意的是,有些构造不是继承的。


标准怎么说?

12.9 继承构造函数 [class.inhctor]

3对于候选继承构造函数集中的每个非模板构造函数,除了没有参数的构造函数或只有单个参数的复制/移动构造函数之外,构造函数都隐式声明具有相同的构造函数特征,除非在using-declaration出现的完整类中有一个用户声明的具有相同签名的构造函数,或者该构造函数为默认构造函数。复制或移动该类的构造函数。

上面的句子可能看起来比它实际上更神秘…它的意思是,用简单的英语来说,一个构造函数只有在using Base::Base的上下文中被继承,如果构造函数;

  • 不是模板,并且;
  • 不是默认构造函数。没有参数),
  • 不是复制/移动构造函数,并且;
  • Derived中没有显式声明匹配通常从Base继承的构造函数

结论

考虑到上面的内容,我们意识到TestBase中接受TestBase const&的构造函数是一个复制构造函数,由于复制构造函数不是继承的,这就是TestChild中不存在的原因。