调用超类构造函数的规则是什么? [英] What are the rules for calling the superclass constructor?
问题描述
从子类1调用超类构造函数的C ++规则是什么?
What are the C++ rules for calling the superclass constructor from a subclass one?
例如,我知道在Java中,你必须将它作为第一行子类构造函数(如果不这样做,则假定对no-arg超级构造函数进行隐式调用 - 如果缺少,则会给出编译错误。)
For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).
推荐答案
如果没有参数,则会自动为您调用基类构造函数。如果要使用参数调用超类构造函数,则必须使用子类的构造函数初始化列表。与Java不同,C ++支持多重继承(无论好坏),因此必须按名称引用基类,而不是super()。
Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".
class SuperClass
{
public:
SuperClass(int foo)
{
// do something with foo
}
};
class SubClass : public SuperClass
{
public:
SubClass(int foo, int bar)
: SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
{
// do something with bar
}
};
More info on the constructor's initialization list here and here.
这篇关于调用超类构造函数的规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!