【问题标题】:Can I std::bind a base class' constructor so that the derived doesn't need to call it explicitly?我可以 std::bind 基类的构造函数,以便派生不需要显式调用它吗?
【发布时间】:2013-08-20 12:35:55
【问题描述】:

我有一个抽象基类,它需要一些对象传递给它的构造函数来初始化它的成员。但我想摆脱通过派生类构造函数传递这些对象。

class Derived : public Base
{
public:
    Derived(type one, type two, type three) : Base(one, two, three)
    {
        // ...

传递给基类的对象是所有创建的派生类的相同实例。有没有办法将它们绑定到基类的构造函数,这样我就不必通过派生类的构造函数转发它们?

// do some magic
// ...

class Derived : public Base
{
    // no need for an explicit constructor anymore
    // ...

【问题讨论】:

  • 您确定std::bind 与此有关吗?
  • std::bind 允许将值绑定到函数参数。我正在为基类的类构造函数寻找类似的东西。

标签: c++ inheritance constructor stdbind


【解决方案1】:

在 C++11 中,您可以将构造函数继承到基类。看来这大致可以满足您的需要:

class derived
    : public base {
public:
    using base::base;
    // ...
};

【讨论】:

  • 能否提供一个示例,说明如何在使用继承的构造函数将参数传递给基类的同时构造派生类?
  • @danijar:我不认为我理解您的要求:您将创建一个派生对象,将基类采用的参数传递给它。如果你提到实现派生类的构造函数,你根本不会实现它!如果您需要在派生类中进行自定义初始化,您可以将其纳入派生成员的构造中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-07
  • 2017-10-31
  • 1970-01-01
  • 2014-04-15
  • 2016-07-19
  • 2018-07-21
  • 2020-04-07
相关资源
最近更新 更多