c++继承:在头文件中调用基类构造函数
C++ Inheritance: Calling Base Class Constructor In Header
假设类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) {
}
相关文章:
- 使用基类指针调用基类的值构造函数的语法是什么?
- 在初始化列表之外手动调用基类的构造函数
- 继承:调用基类的成员和方法
- 在成员构造函数之后调用基类构造函数
- C++初始化之前派生类调用基类的方法
- 如何在具有相同函数名称的派生类中调用基类的函数
- 有没有办法在C++中调用基类的所有子类函数?
- C++:在派生类成员上调用基类方法
- 添加字符串类型的类成员会导致调用基类函数而不是子函数
- 有没有办法调用基类函数,该函数在使用私有继承的派生类中被覆盖?
- 如何在C++中调用基类虚函数
- 如何让派生类在调用基类之前执行操作?
- 在调用基类之前需要在成员上调用方法
- 调用基类克隆实现
- 在派生类中调用基类方法,而无需指定基类名称
- 从参数包中派生的调用基类运算符 =
- 当应该调用派生类方法时,为什么要调用基类方法
- 调用基类函数时强制使用类名?
- 无法从派生的一个方法调用基类方法
- 当派生类无法轻易将参数传递到基类时,如何调用基类构造函数