gpt4 book ai didi

c++ - 构造函数继承和自定义构造函数

转载 作者:太空狗 更新时间:2023-10-29 21:21:24 26 4
gpt4 key购买 nike

使用这个层次结构:

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 Inheriting Constructors [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 中不存在的原因。

关于c++ - 构造函数继承和自定义构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22534997/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com