C++ 子类构造初始化父类
时间: 2023-08-04 13:07:49 浏览: 167
在 C++ 中,子类构造函数可以通过初始化列表来调用父类的构造函数进行初始化。初始化列表是在子类构造函数的定义中使用冒号(:)后面的部分。
以下是一个示例代码,展示了如何在子类构造函数中初始化父类:
#include <iostream>
class Parent {
public:
Parent(int value) {
std::cout << "Parent constructor" << std::endl;
// 父类的构造函数逻辑
}
};
class Child : public Parent {
public:
Child(int value) : Parent(value) {
std::cout << "Child constructor" << std::endl;
// 子类的构造函数逻辑
}
};
int main() {
Child child(10);
return 0;
}
在上述示例中,Child
是从 Parent
派生出来的子类。在 Child
的构造函数中,通过使用初始化列表 : Parent(value)
,来调用 Parent
类的构造函数并传递相应的参数 value
。
当创建 Child
对象时,首先会调用 Parent
的构造函数,然后再调用 Child
的构造函数。运行上述代码会输出以下结果:
Parent constructor
Child constructor
这表明父类构造函数先于子类构造函数被调用。通过这种方式,可以在子类构造函数中初始化父类。
相关推荐
















