构造函数如何在C ++中选择基类构造函数

时间:2015-06-23 01:34:09

标签: c++ constructor

如果你在派生类的构造函数中,并且没有对基类构造函数进行显式调用,那么编译器如何知道要使用哪个基本构造函数?

2 个答案:

答案 0 :(得分:3)

如果构造函数initializer list中未提及基类,则它将为default initialized。由于基类肯定是类类型,这意味着将调用default constructor

其中两个引用也有派生类的示例,它们隐式调用基类的默认构造函数。例如:

struct Class : public Base
{
    unsigned char x;
    unsigned char y;

    Class ( int x )
      : Base ( 123 ), // initialize base class
        x ( x ),      // x (member) is initialized with x (parameter)
        y { 0 }       // y initialized to 0
    {}                // empty compound statement

    Class ( double a )
      : y ( a+1 ),
        x ( y ) // x will be initialized before y, its value here is indeterminate
    {} // base class constructor does not appear in the list, it is
       // default-initialized (not the same as if Base() were used, which is value-init)

   ...
};

答案 1 :(得分:1)

它使用默认构造函数,如N4140中的标准所规定的初始化基础和成员,§12.6.2[class.base.init] / 8(强调我的):

  

在非委托构造函数中,如果给定的可能构造的子对象未由 mem-initializer-id 指定   (包括没有 mem-initializer-list 的情况,因为构造函数没有 ctor-initializer ),   然后

     
      
  • 如果实体是一个非静态数据成员,其中包含大括号或等号初始值

         
        
    • 构造函数的类是一个联合,并且 mem-initializer-id
    • 没有指定该联合的其他变体成员   
    • 构造函数的类不是联合,并且,如果实体是匿名联合的成员,则该联合的其他成员不是由 mem-initializer-id 指定的,
    •   
         

    按照8.5;

  • 中的规定初始化实体   
  • 否则,如果实体是匿名联合或变体成员,则不执行初始化;

  •   
  • 否则,实体默认初始化
  •   

请注意,基类是可能构建的子对象,每个特殊成员函数,§12[特殊] / 5:

  

对于一个类,它的非静态数据成员,它的非虚拟直接基类,如果该类不是抽象的,它的虚拟基类被称为它可能构造的子对象。