构造函数继承和自定义构造函数
Constructor inheritance and custom constructors
使用这个层次结构:
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
中不存在的原因。
相关文章:
- 在类构造函数中定义结构变量的参数
- 为什么为派生类定义复制构造函数需要定义基类的默认构造函数?
- 构造函数中定义的类函数的默认参数
- C++:在共享对象中调用抽象基类构造函数/未定义的符号
- 链表复制构造函数 |未定义的行为
- 如何在类的构造函数中定义成员向量的大小
- Pimpl with unique_ptr : 为什么我必须将接口构造函数的定义移动到".cpp"?
- 我们可以在构造函数中定义静态类成员吗?
- 错误 LNK2005:构造函数已定义
- C++在类构造函数中定义了一个常量成员变量
- 如何在标题文件之外制作构造函数的定义
- 成员函数自定义类型在C++中返回"不命名类型"错误
- 是否可以在声明构造函数的头文件中提供构造函数的定义
- C++:在构造函数中定义类的问题
- 继承的构造函数的定义(主体)是什么样的
- C++构造函数未定义的引用
- 错误LNK2005构造函数已定义
- 在自己的模板类的构造函数中定义并调用模板函数
- 用C++中的参数在构造函数中定义自己类的数组
- C++,为什么我不能把带有参数的类构造函数的定义-初始化列表放在类声明之外