在子类中不想调用默认构造函数时,可以使用参数化构造函数,并在其中调用父类的构造函数。示例如下:
class Parent {
public:
Parent(int x) {
std::cout << "Parent constructor called with " << x << std::endl;
}
};
class Child : public Parent {
public:
Child(int y) : Parent(y) {
std::cout << "Child constructor called with " << y << std::endl;
}
};
int main() {
Child c(10);
return 0;
}
在这个例子中,子类Child的构造函数使用参数y,并且通过调用父类构造函数Parent(y)来初始化父类。因此,不会调用默认构造函数来初始化父类。运行程序后,会输出如下内容:
Parent constructor called with 10
Child constructor called with 10
上一篇:不想在系列中重复一个项目n次。