【问题标题】:Virtual inheritance and default constructor虚拟继承和默认构造函数
【发布时间】:2018-04-18 22:56:33
【问题描述】:

这是一个示例代码:

#include <iostream>
#include <utility>
using namespace std;

struct D;
struct X {};
struct Y {};


template <typename T>
struct A    // A : ASequencialPlanningJobQueueFactory
{
    A() = delete;
    A(T* t) { cout << "A constructor" << endl; }
};

struct B : A<B>    // B : AThermostatedRotorJobQueueFactory
{
    B(B* b, const X& x, const Y& y) : A(b) { cout << "B constructor" << endl; }
};

template <typename T>
struct C : T    // C : PlanningJobQueueFactoryStub
{
    template <typename... Args>
    C(Args&&... args) : T(std::forward<Args>(args)...) { cout << "C constructor" << endl; }
};

struct D : C<B>     // D: ThermostatedRotorJobQueueFactoryStub
{
    D(const X& x, const Y& y) : C(this, x, y) { cout << "D constructor" << endl; }
};

int main()
{
    X x;
    Y y;

    D d(x, y);
    cout << "----------" << endl;

    return 0;
}

如果我给 B 添加一个虚拟继承,如下所示:

struct B : virtual A<B>
{
    B(B* b, const X& x, const Y& y) : A(b) { cout << "B constructor" << endl; }
};

代码不再编译。为什么?

找到错误的时间很长。 Clang 和 gcc 不是很有帮助...

【问题讨论】:

  • 为了帮助人们回答您的问题,您需要更具体地说明错误。请edit 您的帖子包含您从minimal reproducible example 获得的确切错误(最好使用复制+粘贴以避免转录错误)。

标签: c++ virtual


【解决方案1】:

使用虚继承,最派生类应该调用虚基构造函数,所以:

struct D : C<B>     // D: ThermostatedRotorJobQueueFactoryStub
{
    D(const X& x, const Y& y) : A(this), C(this, x, y) { cout << "D constructor" << endl; }
};

C&lt;B&gt; 也是如此:

template <>
struct C<B> : B
{
    template <typename... Args>
    C(Args&&... args) : A(this), B(std::forward<Args>(args)...) {
        cout << "C constructor" << endl;
    }
};

【讨论】:

  • 啊,是的...非常感谢!!
猜你喜欢
  • 2021-06-02
  • 2012-07-26
  • 1970-01-01
  • 2016-03-24
  • 2015-06-21
  • 2015-07-09
  • 2013-10-24
  • 2012-04-12
相关资源
最近更新 更多