什么是构造函数继承? [英] What is constructor inheritance?

查看:118
本文介绍了什么是构造函数继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11中,继承构造函数是什么意思?如果是我认为它是(基类构造函数是在派生类的范围内),它是什么对我的代码有什么影响?这样的功能的应用是什么?

In C++11, what is meant by inheriting the constructor? If it is what i think it is (Base class constructor is brought in the scope of the derived class), what are its implications on my code? What are the applications of such a feature?

推荐答案

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

Inheriting Constructors means just that. A derived class can implicitly inherit constructors from its base class(es).

语法如下:

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

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

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

So now D has the following constructors implicitly defined:

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

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

Ds members are default constructed by these inherited constructors.

它的构造函数定义如下:

It is as though the constructors were defined as follows:

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

这个功能没有什么特别的。

The feature isn't anything special. It is just a shorthand to save typing boilerplate code.

这里是血腥的细节:


12.9继承构造函数



1)使用声明命名一个构造函数隐式声明一个
继承构造函数集合。使用声明中从X类命名的继承的
构造函数的候选集合包括实际构造函数的
和从默认参数的
变换产生的概念构造函数,如下:

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:


  • 所有非模板构造函数的X和

  • 一个带默认参数的参数,
    从省略任何省略号参数规范的结果中得到的构造函数集,
    从参数类型列表的结尾
    中连续省略带有默认参数的参数,和

  • 所有X的构造函数模板,以及

  • 对于每个具有至少一个带有默认参数的参数的构造函数模板,构造函数模板
    从忽略任何省略号参数规范和连续
    省略参数从
    参数类型列表的末尾使用默认参数


    • 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

    这篇关于什么是构造函数继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆