在C++的继承类中,可以通过使用构造函数的初始化列表来调用父类的构造函数。通过在子类的构造函数中使用初始化列表,可以指定调用父类的特定构造函数。
以下是在C++继承类中只调用一个构造函数的示例:
#include <iostream>
class Base {
public:
Base(int value) {
std::cout << "Base constructor called with value: " << value << std::endl;
}
};
class Derived : public Base {
public:
Derived(int value) : Base(value) {
// 子类构造函数中使用初始化列表调用父类构造函数
std::cout << "Derived constructor called with value: " << value << std::endl;
}
};
int main() {
Derived derived(10);
return 0;
}
在上述示例中,Derived
类继承自 Base
类。在 Derived
类的构造函数中,使用初始化列表 : Base(value)
来调用 Base
类的构造函数,并传递相应的参数 value
。
输出结果:
Base constructor called with value: 10
Derived constructor called with value: 10
通过使用初始化列表,我们可以在继承类中只调用一个构造函数,并确保父类的构造函数被正确地调用。这样可以避免在子类的构造函数体中重复调用父类的构造函数。
领取专属 10元无门槛券
手把手带您无忧上云