默认构造函数需要调用基类默认构造函数吗? [英] Do default constructors need to call base class default constructors?
问题描述
正在阅读这个答案,并且令我惊讶,建议您必须始终呼叫基类构造函数在派生类构造函数中。如果您只使用默认构造函数,请考虑:
Was reading this answer and it surprised me, the suggestion you must always call a base class constructor in the derived class constructor. What if you are working only with default constructors, consider:
class Bar : public Foo {
private:
int y;
public:
Bar() : Foo(), y(0) {
}
...
这里是否需要调用 Foo()
?
推荐答案
您不需要显式地在构造函数中调用基类构造函数,在这种情况下,编译器隐含地调用默认构造函数,或者如果没有可调用的话,您会收到编译时错误。
同样适用于非POD的成员。
You do not need to explicitly call a base class constructor in your constructor, in which case the compiler implicitly calls the default constructor, or you get a compile-time error, if none is callable.
Same applies to members who are non-POD.
一个替代方案是一个成员初始化列表 only ,包含对类的另一个构造函数的委托,从而创建一个委托构造函数。
An alternative is a member initialiser list only consisting of a delegation to another constructor of your class, thus creating a delegating constructor.
这篇关于默认构造函数需要调用基类默认构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!