c – 虚拟继承强制基类是默认构造的吗?

在以下代码中,编译器请求基类X是默认可构造的.但是,如果我从类Node的继承中删除virtual关键字,那么对成员m_x的访问当然是不明确的,但不再需要类X的默认构造函数.

这是什么原因?

#include <iostream>

struct Apply
{
    template< typename T >
    struct Node : virtual T    // this line contains the virtual inheritance
    {
        template< typename ...Args>
        Node( Args... args )
            : T( args... )
        {}
    };

    template < typename ...BaseClasses>
    struct Inheritance;

    template < typename FirstBaseClass, typename ...OtherBaseClasses>
    struct Inheritance< FirstBaseClass, OtherBaseClasses... >   : FirstBaseClass
            , Inheritance< OtherBaseClasses... >
    {
        template< typename ...Args>
        Inheritance( Args... args )
            : FirstBaseClass( args... )
            , Inheritance< OtherBaseClasses... >( args... )
        {

        }
    };
};

template < >
struct Apply::Inheritance< >
{
    template< typename ...Args>
    Inheritance( Args... args ){}
};

struct X
{
    X(int i){}

    int m_x;
};

struct A : Apply::Node< X >
{
    A( int i )
        : Apply::Node< X >( i )
        , m_a( i )
    {

    }
    int m_a;
};


struct B : Apply::Node< X >
{
    B( int i )
        : Apply::Node< X >( i )
        , m_b( i )
    { }

    int m_b;
};

struct C : Apply::Node< X >
{
    C( int i )
        : Apply::Node< X >( i )
        , m_c( i )
    { }

    int m_c;
};

struct Example : Apply::Inheritance< A, B, C >
{
    Example( int i )
        : Apply::Inheritance< A, B, C >( i )
    { }

    void print( ) const
    {
        // this line needs the virtual inheritance
        std::cout << m_x << std::endl;

        std::cout << m_a << std::endl;
        std::cout << m_b << std::endl;
        std::cout << m_c << std::endl;
    }
};

int main()
{
    Example ex( 10 );

    ex.print( );

    return 0;
}
最佳答案
类的初始化顺序如下[class.base.init]:

In a non-delegating constructor, initialization proceeds in the following order:
— First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in
the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes,
where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.

您的层次结构是A – >节点< X> - > X,所以初始化的第一件事是X,因为它是一个虚拟的基类.它没有在mem-initializer中指定,因此插入了隐式默认构造:

A( int i )
    : X() // <== implicit 
    , Node< X >( i )
    , m_a( i )
{

}

由于X不是默认可构造的,因此您会收到该错误.你可以通过明确提供正确的东西来解决这个问题:

A( int i )
    : X(i)
    , Node< X >( i )
    , m_a( i )
{

您不必担心X被构造两次,因为虚拟基类只是为最派生的类构建的……这将是A而不是Node< X>.

转载注明原文:c – 虚拟继承强制基类是默认构造的吗? - 代码日志