使用这个层次结构:
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&&’
A 使用声明命名构造函数隐式声明了一组继承的构造函数,但值得注意的是,有些构造函数不是继承的。
标准怎么说?
12.9 继承构造函数 [class.inhctor]
3 For each non-template constructor in the candidate set of inherited constructors other than a constructor having no parameters or a copy/move constructor having a single parameter, a constructor is implicitly declared with the same constructor characteristics unless there is a user-declared constructor with the same signature in the complete class where the using-declaration appears or the constructor would be a default, copy ,or move constructor for that class.
上面的句子可能看起来更神秘,但它实际上是这样的。用简单的英语来说,它的意思是构造函数仅在上下文中被继承using Base::Base
如果构造函数;
- 不是模板,并且;
- 不是默认构造函数(即没有参数),并且;
- 不是复制/移动构造函数,并且;
- 中没有明确声明
Derived
与通常继承自的构造函数匹配Base
结论
考虑到上述内容,我们意识到构造函数TestBase
这需要一个TestBase const&
是一个复制构造函数,并且由于复制构造函数不是继承的,这就是它不存在于TestChild
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)