从派生类调用基类构造函数的C++规则是什么?

例如,我知道在Java中,您必须作为子类构造函数的第一行执行此操作(如果不这样做,则假定对无参数超级构造函数的隐式调用-如果缺少,则会给您一个编译错误)。


当前回答

如果在基构造函数中有默认参数,则将自动调用基类。

using namespace std;

class Base
{
    public:
    Base(int a=1) : _a(a) {}

    protected:
    int _a;
};

class Derived : public Base
{
  public:
  Derived() {}

  void printit() { cout << _a << endl; }
};

int main()
{
   Derived d;
   d.printit();
   return 0;
}

输出为:1

其他回答

每个人都提到通过初始化列表调用构造函数,但没有人说可以从派生成员的构造函数体显式调用父类的构造函数。例如,请参阅从子类的构造函数体调用基类的构造函数的问题。重点是,如果在派生类的主体中使用对父类或超级类构造函数的显式调用,这实际上只是创建父类的实例,而不是在派生对象上调用父类构造函数。在派生类对象上调用父类或超级类构造函数的唯一方法是通过初始化列表,而不是在派生类构造函数体中。因此,也许它不应该被称为“超类构造函数调用”。我把这个答案放在这里是因为有人可能会(像我一样)感到困惑。

CDerived::CDerived()
: CBase(...), iCount(0)  //this is the initialisation list. You can initialise member variables here too. (e.g. iCount := 0)
    {
    //construct body
    }

如果在基构造函数中有默认参数,则将自动调用基类。

using namespace std;

class Base
{
    public:
    Base(int a=1) : _a(a) {}

    protected:
    int _a;
};

class Derived : public Base
{
  public:
  Derived() {}

  void printit() { cout << _a << endl; }
};

int main()
{
   Derived d;
   d.printit();
   return 0;
}

输出为:1

如果基类构造函数没有参数,它们将自动为您调用。如果要使用参数调用超类构造函数,则必须使用子类的构造函数初始化列表。与Java不同,C++支持多重继承(无论好坏),因此基类必须按名称引用,而不是“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
        }
};

有关构造函数初始化列表的更多信息,请点击此处。

当一个类从多个类派生时,没有人提到构造函数调用的顺序。该序列如派生类时所述。