【问题标题】:Implicitly passing parameter(s) to base constructor C++将参数隐式传递给基本构造函数 C++
【发布时间】:2019-01-06 13:56:26
【问题描述】:

我对@9​​87654321@ 提出的完全相同的问题感兴趣, 但对于 C++。有没有办法隐式传递参数 基类构造函数?这是我尝试过的一个小例子 这是行不通的。当我移除 cmets 并 调用基地时 类构造函数显式,一切正常。

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);
              ^

【问题讨论】:

    标签: c++ inheritance constructor base-class


    【解决方案1】:

    您可以通过将Base 类构造函数拉入Derived 类的范围来实现:

    class Derived : public Base
    {
    public:
        using Base::Base;  // Pull in the Base constructors
    
        // Rest of class...
    };
    

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

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

    【讨论】:

    • 显然 +1 7 秒前发布 :)
    【解决方案2】:

    你可以像这样把所有基类的构造函数带入子类的作用域

    class Derived : public Base {
      public:
        using Base::Base;
    
      /* ... */
    };
    

    这完全允许使用场景

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

    请注意,using Base::Base 总是提供由Base 声明的所有 构造函数。没有办法省略一个或多个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多