繁体   English   中英

C ++用参数委托ctor和parent 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

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

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

什么是首选解决方案?

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

因此,您应该从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()

它背后的基本原理是当你有两个“部分专业化”的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.
};

我相信技术原因在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*/};
};

B(const A& a) : A(a), B()因为没有意义B() 将初始化的基类A 这基本上是一个重复的初始化,这是一个固有的矛盾。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM