将参数隐式传递给基本构造函数 C++

Implicitly passing parameter(s) to base constructor C++

我对 提出的完全相同的问题很感兴趣, 但对于 C++。有没有办法隐式传递参数 到 base class 构造函数 ?这是我试过的一个小例子 这是行不通的。当我删除评论并 调用 base class 显式构造函数,一切正常。

struct Time { int day; int month; };
class Base {
public:
    Time time;
    Base(Time *in_time)
    {
        time.day   = in_time->day;
        time.month = in_time->month;
    }
};
class Derived : public Base {
public:
    int hour;
    // Derived(Time *t) : Base(t) {}
};
int main(int argc, char **argv)
{
    Time t = {30,7};
    Derived d(&t);
    return 0;
}

如果有帮助,这是完整的编译行+编译错误:

$ g++ -o main main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:19:14: error: no matching function for call to ‘Derived::Derived(Time*)’
  Derived d(&t);
              ^

您可以通过将 Base class 构造函数拉入 Derived class:

的范围来实现
class Derived : public Base
{
public:
    using Base::Base;  // Pull in the Base constructors

    // Rest of class...
};

顺便说一句,我真的不建议使用指针。在这种情况下,根本不需要它。而是按值传递。这将使您的 Base 构造函数更加简单:

Base(Time in_time)
    : time(in_time)
{}

您可以像这样将所有基础 class 构造函数带入子class 的范围

class Derived : public Base {
  public:
    using Base::Base;

  /* ... */
};

这完全符合使用场景

Time t = {30,7};
Derived d(&t);

请注意,using Base::Base 始终附带 所有 个由 Base 声明的构造函数。没有办法省略一个或多个。