调用基类构造函数的规则是什么? [英] What are the rules for calling the base class constructor?

查看:70
本文介绍了调用基类构造函数的规则是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What are the C++ rules for calling the base class constructor from a derived class?

例如,我知道在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆