c++继承:在头文件中调用基类构造函数

C++ Inheritance: Calling Base Class Constructor In Header

本文关键字:调用 基类 构造函数 文件 继承 c++      更新时间:2023-10-16

假设类Child是类Parent的派生类。在一个有5个文件的程序中,我如何在Child.h中指定我想调用Parent的构造函数?我认为像下面这样的内容在header中是不合法的:

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

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

在Child.h中,只需声明:

Child(int Param, int ParamTwo);

在Child.cpp中,您将拥有:

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

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

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) {
}