C ++超类构造函数调用规则 [英] C++ superclass constructor calling rules

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

问题描述

什么是C ++规则从子类调用超类构造函数?

What are the C++ rules for calling the superclass constructor from a subclass one??

例如,我知道在Java中,你必须做为子类构造函数的第一行(如果你不隐式调用一个无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.

这篇关于C ++超类构造函数调用规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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