C++用参数委托ctor和parent ctor

Gau*_*ier 2 c++ constructor initializer-list c++11

这在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
    {};
  // ...
};
Run Code Online (Sandbox Code Playgroud)

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

我如何用参数调用父类的构造函数,并调用B类的基本构造函数?(我在B中有一堆其他需要相同行为的构造函数).

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

什么是首选解决方案?

luk*_*k32 5

我认为首选的委托方式是另一种方式,它不是用于重构构造函数的公共部分,而是将更简单的方法定义为更复杂情况的特例.

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

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

A()在创建时你仍然在打电话B.

它背后的基本原理是当你有两个"部分专业化"的c'tors时,你将无法使用它们初始化复杂的c'tors.例如:

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

我相信技术原因在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!
};
Run Code Online (Sandbox Code Playgroud)

这是继承中已知的钻石问题.解决方案是扭转逻辑.

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*/};
};
Run Code Online (Sandbox Code Playgroud)