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

时间:2014-03-20 13:48:28

标签: c++ inheritance c++11

使用此层次结构:

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(使用'关键字),但事实上它是因为编译器生成了一个默认的复制构造函数,它调用了复制父类的构造函数,是否正确?

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

但为什么测试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&&’

1 个答案:

答案 0 :(得分:3)

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


标准说什么?

  

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

     
    

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

  

上面的句子可能看起来更加神秘,它实际上是......用简单的英语说的是构造函数只在构造函数的using Base::Base的上下文中继承;

  • 不是模板,而且;
  • 不是默认构造函数(即没有参数),和;
  • 不是复制/移动构造函数,而是;
  • Derived中没有明确声明与通常从Base继承的构造函数匹配

结论

考虑到上述情况,我们意识到TestBase中带有TestBase const&的构造函数是一个复制构造函数,并且由于复制构造函数不是继承的,因此它是非复制构造函数的原因出现在TestChild