【问题标题】:C++ Inheritance: Calling Base Class Constructor In HeaderC++ 继承:在标头中调用基类构造函数
【发布时间】:2014-07-25 16:13:42
【问题描述】:

假设类Child 是类Parent 的派生类。在一个五文件程序中,如何在Child.h 中指定我要调用Parent 的构造函数?我认为标题中的以下内容不合法:

Child(int Param, int ParamTwo) : Parent(Param);

在这种情况下,Child.cpp 的构造函数语法应该是什么样的?

【问题讨论】:

标签: c++ inheritance syntax inline initializer-list


【解决方案1】:

在 Child.h 中,您只需声明:

Child(int Param, int ParamTwo);

在 Child.cpp 中,您将拥有:

Child::Child(int Param, int ParamTwo) : Parent(Param) {
    //rest of constructor here
}

【讨论】:

  • 如果我没有 .cpp 文件并且它类似于接口怎么办?
【解决方案2】:

构造函数的初始化列表是其定义的一部分。您可以在类声明中内联定义它

class Child : public Parent {
    // ...
    Child(int Param, int ParamTwo) : Parent(Param)
    { /* Note the body */ }
};

或者直接声明

class Child : public Parent {
    // ...
    Child(int Param, int ParamTwo);
};

并在编译单元中定义(Child.cpp

Child::Child(int Param, int ParamTwo) : Parent(Param) {
}

【讨论】:

  • +1 顺便说一句:使用 implementation 而不是 definition 可能会减少误导。
猜你喜欢
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多