gpt4 book ai didi

c++ - 什么是构造函数继承?

转载 作者:太空宇宙 更新时间:2023-11-04 12:45:54 27 4
gpt4 key购买 nike

在C++11中,继承构造函数是什么意思?如果它是我认为的那样(基类构造函数被引入派生类的范围),它对我的​​代码有什么影响?这种特性有哪些应用?

最佳答案

继承构造函数就是这个意思。派生类可以从其基类隐式继承构造函数。

语法如下:

struct B
{
B(int); // normal constructor 1
B(string); // normal constructor 2
};

struct D : B
{
using B::B; // inherit constructors from B
};

所以现在 D 具有以下隐式定义的构造函数:

D::D(int); // inherited
D::D(string); // inherited

Ds 成员默认由这些继承的构造函数构造。

就好像构造函数定义如下:

D::D(int x) : B(x) {}
D::D(string s) : B(s) {}

该功能没有什么特别之处。它只是一种节省键入样板代码的简写方式。

这里是血淋淋的细节:

12.9 Inheriting Constructors

1) A using-declaration that names a constructor implicitly declares a set of inheriting constructors. The candidate set of inherited constructors from the class X named in the using-declaration consists of actual constructors and notional constructors that result from the transformation of defaulted parameters as follows:

  • all non-template constructors of X, and
  • for each non-template constructor of X that has at least one parameter with a default argument, the set of constructors that results from omitting any ellipsis parameter specification and successively omitting parameters with a default argument from the end of the parameter-type-list, and
  • all constructor templates of X, and
  • for each constructor template of X that has at least one parameter with a default argument, the set of constructor templates that results from omitting any ellipsis parameter specification and successively omitting parameters with a default argument from the end of the parameter-type-list

关于c++ - 什么是构造函数继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51616966/

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