[英]using default constructor in constructor inheritance
I have a template class "Derived" which does a constructor inheritance: 我有一个模板类“ Derived”,它可以进行构造函数继承:
template <class T>
class Derived : public T
{
using T::T;
Derived()
{
std::cout<<"in derived";
}
};
My base class has a constructor that expects arguments: 我的基类有一个需要参数的构造函数:
class Base
{
public:
Base(int a)
{
std::cout<<"in base";
}
};
When I create an object of type Derived it seems the derived constructor is not called: 当我创建派生类型的对象时,派生构造函数似乎没有被调用:
Derived<Base> derived(2);
prints "in base"; 打印“基础”;
Why? 为什么? Is there a way to tell it to call Derived constructor? 有没有办法告诉它调用派生构造函数?
Initialization by an inherited constructor happens as follows: 继承的构造函数进行的初始化如下:
[class.inhctor.init] (emphasis mine) [class.inhctor.init] (强调我的)
1 When a constructor for type B is invoked to initialize an object of a different type D (that is, when the constructor was inherited), initialization proceeds as if a defaulted default constructor were used to initialize the D object and each base class subobject from which the constructor was inherited, except that the B subobject is initialized by the invocation of the inherited constructor . 1当调用类型B的构造函数初始化不同类型D的对象时(即,继承该构造函数时), 初始化将继续进行,就好像使用默认的默认构造函数来初始化D对象和来自该对象的每个基类子对象一样构造函数是继承的,除了B子对象是通过调用继承的构造函数初始化的 。 The complete initialization is considered to be a single function call; 完整的初始化被认为是单个函数调用。 in particular, the initialization of the inherited constructor's parameters is sequenced before the initialization of any part of the D object. 特别是,在初始化D对象的任何部分之前,先对继承的构造函数的参数进行初始化。
The key point is the defaulted word. 关键是默认单词。 Defaulted c'tors are generated by the compiler, for instance a copy c'tor can be defaulted. 默认的c'tor由编译器生成,例如,副本c'tor可以默认。 And so it doesn't use any c'tor that's defined in the derived class. 因此,它不使用派生类中定义的任何c'tor。 A compiler generated c'tor is always going to have an empty compound statement. 编译器生成的c'tor总是会有一个空的复合语句。 So one should not expect anything to be printed. 因此,不应期望会打印任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.