C++ 使用参数委托 ctor 和父 ctor

C++ delegating ctor and parent ctor with argument

这在 C++11 中似乎不起作用:

class B : public A
{
  public:
    B(const A& a)
        : A(a)   // parent constructor for passing the parameter
        , B()    // delegating constructor for init of other members
    {};
  // ...
};

gcc 告诉我 an initializer for a delegating constructor must appear alone.

如何既调用带参数的父class的构造函数,又调用Bclass的基本构造函数? (我在 B 中有一堆其他构造函数需要相同的行为)。

现在我正在考虑编写一个私有 B::init() 函数并在所有构造函数主体中使用它,但这有点像 C++03。

首选解决方案是什么?

B(const A& a) : A(a), B() 没有意义,因为 B() 也会 初始化基数 class A。这本质上是一个重复的初始化,这是一个内在的矛盾。

如果您使用委托构造函数,该语言唯一真正的选择是禁止任何其他操作。这就是你的编译器告诉你的。

我认为委托的首选方式是相反的方式,它并不意味着用于重构构造函数的公共部分,而是将更简单的委托定义为更复杂情况的特例。

所以你应该从 B(const A& a) 开始并将其用作委派目标。

class B : public A
{
  public:
    B() : B(A());
    B(const A& a) : A(a)   // parent constructor for passing the parameter
    {};
};

您在创建 B 时仍然调用 A()

其背后的基本原理是当您有两个 "partially specialized" c'tor 时,您将无法使用它们来初始化复杂的。例如:

class B : public A
{
  public:
    B() {};
    B(int) : B() {};
    B(double) : B() {};
    B(double,int) : B(int), B(double) {}; // can't do it.
};

我相信 Bathsheba 的回答中解释了技术原因。看看如果你在 B():

中有共同部分会发生什么
class B : public A
{
  public:
    B() {};
    B(int) : B() {};
    B(double) : B() {};
    B(double,int) : B(int), B(double) {}; //ooops would get B() called twice!
};

这是继承已知的钻石问题。解决办法就是反逻辑。

class B : public A
{
  public:
    B() : B(0,0) {};
    B(int a) : B(a,0) {};
    B(double d) : B(0,d) {};
    B(double a, int d) {/*full implementation*/};
};